Save a PDF from a WKWebView



这个问题与macOS有关,而不是iOS。

请注意,此问题被报告为此问题的副本。该页面上的答案要么与iOS(无关紧要(有关,要么使用已弃用的WebView作为解决方案,这正是我的问题

。因此,Apple已弃用WebView以支持WKWebView,但是我没有看到能够从新视图类型导出(或打印(PDF的工作解决方案。我已经从委托方法中尝试了以下(以及更多(webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

1.

let pdfData = webView.dataWithPDF(inside: webView.frame)
try? pdfData.write(to: URL(fileURLWithPath: "/filepath/to/test.pdf"))

这导致了一个文字空白的 pdf 文件。

阿拉伯数字。

webView.takeSnapshot(with: nil) { (image, error) in
if let error = error {
print("Error: (error)")
return
}
guard let image = image else {
print("No image")
return
}
try? image.tiffRepresentation?.write(to: URL(fileURLWithPath: "/path/to/test.tif"))
}

虽然这在图像中获得了实际内容,但它是一个(巨大的(渲染位图图像,丢失了所有文本/字符串数据,这些数据也只显示屏幕上可见的内容,除了窗口边缘之外没有任何内容。

同时,按照 Web 上提供的大量示例,使用 WebView 效果很好,而且符合预期。我是相信苹果发布了一个不推荐使用的框架的半生不熟的替代品,还是我做错了什么?

现在可以通过WKWebViewcreatePDF方法实现: https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf

下面是一个示例:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let config = WKPDFConfiguration()

//Set the page size (this can match the html{} size in your CSS
config.rect = CGRect(x: 0, y: 0, width: 792, height: 612)

//Render the PDF
webView.createPDF(configuration: config){ result in
switch result{
case .success(let data):
try! data.write(to: URL(fileURLWithPath: "/path/file.pdf"))
case .failure(let error):
print(error)
}
}
}

我让它在macOS和iOS上运行。希望这有所帮助。

最新更新