How to print the content of a WKWebView
using printOperation(with:)?
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.
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?
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)