3

I made a webView present a given HTML string, using this code:

let filePath = Bundle.main.path(forResource: "my file name", ofType: "html")
let htmlStr = try! NSString.init(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlStr as String, baseURL: nil)

the webView present the HTML correctly but when I try to print it the print panel appear with blank page, I used this:

webView.printView(nil)

also I tried this:

NSPrintOperation(view: webView).run()

All appeared print panel with blank page! Any help?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Nayef
  • 463
  • 5
  • 13
  • Duplicate: https://stackoverflow.com/questions/18216560/webview-osx-not-rendering-in-print-panel-preview?rq=1 – El Tomato Oct 17 '17 at 00:15
  • In new Swift no more (mainFrame) property in WKWebView, so how I can convert this to new Swift: NSPrintOperation(view: webView.mainFrame.frameView.documentView).runOperation() – Nayef Oct 17 '17 at 12:31
  • Read the documentation. https://developer.apple.com/documentation/webkit/webview – El Tomato Oct 17 '17 at 12:57
  • The document says: Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView – Nayef Oct 17 '17 at 23:16
  • In WKWebView there is no webFrame .. also in documentation there is no explain how to print the webView .. see: https://developer.apple.com/documentation/webkit/wkwebview – Nayef Oct 17 '17 at 23:18
  • I'm running into this same issue. Have you figured out how to print to PDF on macOS? – Clifton Labrum Mar 28 '20 at 18:00

1 Answers1

0

run() doesn't work with WKWebView on OSX. Use runModal(for:delegate:didRun:contextInfo) instead. Example:

let printInfo = NSPrintInfo.shared
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .automatic
printInfo.isVerticallyCentered = true
printInfo.isHorizontallyCentered = true
printInfo.orientation = .portrait
printInfo.topMargin = 20
printInfo.bottomMargin = 20
printInfo.rightMargin = 20
printInfo.leftMargin = 20

let op = self.webView.printOperation(with: printInfo)
op.showsPrintPanel = true
op.showsProgressPanel = true
op.view?.frame = self.webView.bounds
op.runModal(for: self.view.window!, delegate: self, didRun: nil, contextInfo: nil)

I got this from: How does one Print all WKWebView On AND Offscreen content OSX and iOS

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 07 '22 at 12:12