I want to print the content of a WKWebView
. I've done some searching, and many people have struggled with this over the years. Some claimed success, but their solutions don't work for me. One person created images for each pages and printed that, but then if you were to print to PDF, you'd get a PDF containing images rather than text.
If I just call the printView(_:))
method of the view, I get blank pages.
With the following more elaborate code, I get a partial printout, 11 out of what should be about 13 pages.
let info = NSPrintInfo.shared
info.topMargin = 72.0;
info.bottomMargin = 72.0;
info.leftMargin = 72.0;
info.rightMargin = 72.0;
info.isVerticallyCentered = false;
info.isHorizontallyCentered = false;
info.horizontalPagination = .fit;
info.verticalPagination = .automatic;
let printOp = webView!.printOperation( with: info )
printOp.canSpawnSeparateThread = true
printOp.view?.frame = NSMakeRect( 0, 0,
info.paperSize.width, info.paperSize.height )
printOp.runModal(for: webView.window!, delegate: self,
didRun: nil, contextInfo: nil )
When I run the above under the debugger, I see console messages saying
CGContextClipToRect: invalid context 0x0.
Once the print dialog appears, if I touch (but not change) the selected printer, then the page count changes to the correct value.