2016-07-04 62 views
5

我想弄清楚如何将WebView保存为PDF并完全卡住,是否真的会感谢一些帮助?将WebView保存为PDF将返回空白图像?

我在可可&斯威夫特在OSX这样做,这是我到目前为止的代码:

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

} 

这很简单,我在做什么是创建一个web视图,写一些基本的HTML内容,它这使得这样的:

View

然后采取的观点,并将其保存为PDF文件,但散发出来的空白:

PDF

我试过抓取webView和视图的内容,但没有喜悦。

我在这里发现了一个类似的问题How to take a screenshot when a webview finished rending关于将webview保存为图片,但到目前为止没有运气与OSX解决方案。

难道这与文档尺寸有关吗? 或内容在子视图中? 也许如果你捕捉视图,你不能捕获子视图?

任何想法?

+0

你好。如果您发现问题的解决方案,*将其作为答案*发布,请勿将其添加到您的问题中。也请不要将“解决”添加到标题中。发布答案并将其标记为已接受是“解决”问题的方式。谢谢。 – Moritz

+0

对不起,会做。 –

+0

没问题 - 我已经恢复了你的编辑,你现在只需要发布你的答案。谢谢! :) – Moritz

回答

1

所以我有点想出如何解决它,事实证明,你不能(特别是在OSX上)访问和打印从WKWebView的Web视图。

你必须使用WebView而不是WKWebView(我最初是用WKWebView开始的,因为我读过的一些文章说要使用它)。

网页视图对象非常类似WKWebView对象,它是地狱:-)

乐趣,但它可以让你访问.mainFrame & .frameView,你将需要打印的内容。

这里是我的代码:

let webView = WebView(frame: self.view.frame) 
    let localfilePath = NSBundle.mainBundle().URLForResource(fileName, withExtension: "html"); 
    let req = NSURLRequest(URL: localfilePath!); 
    webView.mainFrame.loadRequest(req) 
    self.view.addSubview(webView) 

一旦它的渲染后来我加了1秒的延迟,以确保公正之前,我打印的内容已经呈现,

// needs 1 second delay 
    let delay = 1 * Double(NSEC_PER_SEC) 
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
    dispatch_after(time, dispatch_get_main_queue()) { 
     // works! 
     let data = webView.dataWithPDFInsideRect(webView.frame) 
     let doc = PDFDocument.init(data: data) 
     doc.writeToFile("/Users/john/Desktop/test.pdf") 

     // works! 
     let printInfo = NSPrintInfo.sharedPrintInfo() 
     let printOperation = NSPrintOperation(view: webView.mainFrame.frameView, printInfo: printInfo) 
     printOperation.runOperation() 
    } 

这里我打印并将其保存为PDF,这样我就可以确定它在任何情况下都能正常工作。

我相信它可以改进,我讨厌延迟黑客,应该用某种回调或委托代替内容完全加载时运行。