gpt4 book ai didi

swift - 从 WKWebView 保存 PDF

转载 作者:行者123 更新时间:2023-12-05 03:52:03 25 4
gpt4 key购买 nike

此问题适用于 macOS,而非 iOS。

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

因此 Apple 已弃用 WebView 以支持 WKWebView,但我没有看到能够从新的导出(或打印)PDF 的可行解决方案查看类型。我在委托(delegate)方法 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"))
}

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

与此同时,根据网络上提供的大量示例,使用 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 上使用它。希望这会有所帮助。

关于swift - 从 WKWebView 保存 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62423685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com