So, I somehow figured out how to solve it, it turns out you cannot (especially on OSX) access and print the web view from WKWebView.
You should use WebView and NOT WKWebView (I originally started with WKWebView, because some of the articles I read said they use this).
The WebView object is pretty much like the WKWebView object, which is fun as hell :-)
But it gives you access to the .mainFrame and .frameView, which you will need to print.
Here is my code:
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)
After rendering, I added a 1 second delay to make sure the content was displayed before I print it,
// 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() }
Here I print it and save it as a PDF, so I'm sure it works under any circumstances.
I am sure that it can be improved, I hate hacking delays, I have to replace it with some kind of callback or delegate to run when the content is fully loaded.
source share