Using NSPrintOperation from WKWebView

572 views Asked by At

How to print the content of a WKWebView using printOperation(with:)?

First try

let info = NSPrintInfo.shared
let operation = printOperation(with: info)
operation.run()

But I get a crash with the message:

[Printing] ERROR: The NSPrintOperation view's frame was not initialized properly before knowsPageRange: returned. (WKPrintingView)

But the view property on NSPrintOperation is read only.

Second try

if instead I try to run the operation modally and disable the print panel like this:

operation.showsPrintPanel = false

guard let window = webView.window else { return }

operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil)

I get an alert with the message:

To print this file, you must set up a printer.

And it is true, I haven't setup a printer, but what about printing (i.e. saving) to PDF?

2

There are 2 answers

0
Vicente Garcia On BEST ANSWER

I realised you can modify the view's frame on NSPrintOperation. It has to be a CGRect/NSRect of at least 100x100, apparently it resizes itself afterwards, and the position doesn't matter at all, this is what worked for me at the end:

let info = NSPrintInfo.shared
let operation = webView.printOperation(with: info)
operation.view?.frame = webView.bounds

guard let window = webView.window else { return }

operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil)

0
Todd On

Taking the accepted answer didn't work for me, but a small modification fixed this:

operation.view?.frame = NSRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
guard let window = view.window else { return }
operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil)

Where view.window is (in my case) the main window of the app - the WKWebView was only used to load the HTML for the PDF.