Swift Mac OS:尝试打印 webView(WKWebView)时打印空白页面

3

我使用以下代码使WebView呈现给定的HTML字符串:

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)

webView正确显示HTML内容,但当我尝试打印它时,打印面板出现空白页。我使用了以下代码:

webView.printView(nil)

我也尝试了这个:

NSPrintOperation(view: webView).run()

所有打印面板都出现了空白页面!需要帮助吗?


重复:https://dev59.com/LnXYa4cB1Zd3GeqP8qQq?rq=1 - El Tomato
在新的Swift中,WKWebView中不再有(mainFrame)属性,那么我该如何将其转换为新的Swift:NSPrintOperation(view: webView.mainFrame.frameView.documentView).runOperation()? - Nayef
阅读文档。https://developer.apple.com/documentation/webkit/webview - El Tomato
该文档指出:从iOS 8.0和OS X 10.10开始,使用WKWebView将Web内容添加到您的应用程序中。不要使用UIWebView或WebView。 - Nayef
在WKWebView中没有WebFrame..同时文档中也没有解释如何打印webView..请参见:https://developer.apple.com/documentation/webkit/wkwebview - Nayef
我遇到了同样的问题。你解决了如何在macOS上打印到PDF的问题吗? - Clifton Labrum
1个回答

0

在OSX上,run()与WKWebView不兼容。请改用runModal(for:delegate:didRun:contextInfo)。示例:

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)

我从这里得到的:如何在OSX和iOS上打印所有WKWebView的屏幕内外内容


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接