我想弄清楚如何将WebView保存为PDF并完全卡住,是否真的会感谢一些帮助?将WebView保存为PDF将返回空白图像?
我在可可&斯威夫特在OSX这样做,这是我到目前为止的代码:
import Cocoa
import WebKit
class ViewController: NSViewController {
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
loadHTMLString()
}
func loadHTMLString() {
let webView = WKWebView(frame: self.view.frame)
webView.loadHTMLString("<html><body><p>Hello, World!</p></body></html>", baseURL: nil)
self.view.addSubview(webView)
createPDFFromView(webView, saveToDocumentWithFileName: "test.pdf")
}
func createPDFFromView(view: NSView, saveToDocumentWithFileName fileName: String) {
let pdfData = view.dataWithPDFInsideRect(view.bounds)
if let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
let documentsFileName = documentDirectories + "/" + fileName
debugPrint(documentsFileName)
pdfData.writeToFile(documentsFileName, atomically: false)
}
}
}
这很简单,我在做什么是创建一个web视图,写一些基本的HTML内容,它这使得这样的:
然后采取的观点,并将其保存为PDF文件,但散发出来的空白:
我试过抓取webView和视图的内容,但没有喜悦。
我在这里发现了一个类似的问题How to take a screenshot when a webview finished rending关于将webview保存为图片,但到目前为止没有运气与OSX解决方案。
难道这与文档尺寸有关吗? 或内容在子视图中? 也许如果你捕捉视图,你不能捕获子视图?
任何想法?
你好。如果您发现问题的解决方案,*将其作为答案*发布,请勿将其添加到您的问题中。也请不要将“解决”添加到标题中。发布答案并将其标记为已接受是“解决”问题的方式。谢谢。 – Moritz
对不起,会做。 –
没问题 - 我已经恢复了你的编辑,你现在只需要发布你的答案。谢谢! :) – Moritz