当WKWebView完成加载时,我正在将Swift 4与WKWebView一起使用,我想获取Webview并生成PDF,一切正常,除了我打印时,文本未从WKWebView出现,所有边框和td单元格都没有颜色会显示,但文本不会显示。
这是我的代码:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.stopIndicator()
//Assign the Web View as the View
view = webView
var newheight = CGFloat()
var newwidth = CGFloat()
self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
newheight = height as! CGFloat
self.webView.evaluateJavaScript("document.body.scrollWidth", completionHandler: { (width, error) in
newwidth = width as! CGFloat
//Define the render, an object that draws pages of content that are to be printed, with or without the assistance of print formatters.
let render = UIPrintPageRenderer()
//Assign the Web View to the print page renderer
render.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0)
//Define the page size of the PDF Document
let page = CGRect(x: 0, y: 0, width: newwidth, height: newheight)
//Define the print page size
let printable = page.insetBy(dx: 0, dy: 0)
//Set the size for the render page
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
//Set the size for the render printable
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
let rect = CGRect(x: 0, y: 0, width: newwidth, height: newheight)
//Define the PDF Data variable
let pdfData = NSMutableData()
//Creates a PDF-based graphics context that targets the specified mutable data object.
UIGraphicsBeginPDFContextToData(pdfData, rect, nil)
//For each pages in the render
for i in 0...render.numberOfPages {
//Marks the beginning of a new page in a PDF context and configures it using default values.
UIGraphicsBeginPDFPage();
//Define the current page bounds.
let bounds = UIGraphicsGetPDFContextBounds()
//Draw the page on content
render.drawPage(at: i, in: bounds)
}
//Closes a PDF graphics context and pops it from the current context stack.
UIGraphicsEndPDFContext();
//Get the first directory path.
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
//Write the PDF Data to the file.
pdfData.write(toFile: "\(documentsPath)/pdfName.pdf", atomically: true)
//Set the PDF file path
self.pdfPath = "\(documentsPath)/pdfName.pdf"
//Set the PDF title
self.pdfTitle = "pdfName"
self.shareButton.isEnabled = true
})
})
}
})
}
完成Web视图的加载后,上面的此方法将从Web视图生成PDF,但是问题是没有文本生成。我在做什么错了?