我正在尝试弄清楚如何将WebView保存为PDF并完全卡住,请问真的会有帮助吗?

我正在OSX的Cocoa&Swift中进行此操作,到目前为止,这是我的代码:

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

}

这很简单,我正在做的是创建一个WebView并向它编写一些基本的html内容,从而呈现出以下内容:

swift - 将WebView保存为PDF会返回空白图像吗?-LMLPHP

然后获取 View 并将其保存为PDF文件,但结果为空白:

swift - 将WebView保存为PDF会返回空白图像吗?-LMLPHP

我试图从webView和View抓取内容,但没有任何乐趣。

我在How to take a screenshot when a webview finished rending中发现了与将Webview保存到图像有关的类似问题,但到目前为止,使用OSX解决方案没有运气。

可能与文档尺寸有关吗?
还是内容在 subview 中?
也许如果您捕获 View ,则无法捕获 subview ?

有任何想法吗?

最佳答案

iOS 11.0及更高版本,Apple提供了以下API来捕获WKWebView的快照。

@available(iOS 11.0, *)
    open func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?, completionHandler: @escaping (UIImage?, Error?) -> Swift.Void)

用法示例:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        if #available(iOS 11.0, *) {
            webView.takeSnapshot(with: nil) { (image, error) in
                //Do your stuff with image
            }
        }
    }

iOS 10及更低版本,必须使用UIWebView捕获快照。可以使用以下方法来实现。
func webViewDidFinishLoad(_ webView: UIWebView) {

        let image = captureScreen(webView: webView)
        //Do your stuff with image
    }

func captureScreen(webView: UIWebView) -> UIImage {
        UIGraphicsBeginImageContext(webView.bounds.size)
        webView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

这是另一个相关的answer

关于swift - 将WebView保存为PDF会返回空白图像吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38191642/

10-11 22:23
查看更多