从 WKWebView 保存 PDF

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 文件。

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"))
}

虽然这在图像中获得了实际内容,但它是一个(巨大的)渲染位图图像,已经丢失了所有 textual/string 数据,它也只显示屏幕上可见的内容,没有超出边缘的内容window.

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

现在可以使用 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 上都可以使用它。希望这对您有所帮助。