从 WKWebView 保存 PDF

mre*_*dig 3 pdf macos webkit swift wkwebview

这个问题与 macOS 有关,与 iOS 无关。

请注意,此问题被报告为此问题的重复项。该页面上的答案要么与 iOS 有关(无关),要么使用已弃用的WebView解决方案,这正是我的问题首先要解决的问题。

因此,Apple 已弃用WebViewWKWebView但我没有看到能够从新视图类型导出(或打印)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"))
Run Code Online (Sandbox Code Playgroud)

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

2.

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"))
}
Run Code Online (Sandbox Code Playgroud)

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

同时,根据网络上提供的大量示例,使用 WebView 效果很好并且符合预期。我是否应该相信苹果发布了一个已弃用框架的半成品替代品,或者我做错了什么?

Cli*_*rum 6

现在可以使用 的WKWebView方法createPDFhttps://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)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在 macOS 和 iOS 上都可以使用它。希望这有帮助。