OGeek|极客世界-中国程序员成长平台

标题: ios - 如何从 UIWebView 打印内容? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:28
标题: ios - 如何从 UIWebView 打印内容?

我正在使用 swift,我需要打印在 UIWebView 中打开的工作表。

    let url = webView.request?.url
    let stringurl = url?.absoluteString

    let pic = UIPrintInteractionController.shared
    let printInfo : UIPrintInfo = UIPrintInfo(dictionary: nil)

    printInfo.outputType = UIPrintInfoOutputType.general
    printInfo.jobName = stringurl!

    pic.printInfo = printInfo
    pic.printFormatter = webView.viewPrintFormatter()
    pic.showsPageRange = false

    pic.present(animated: true, completionHandler: nil)



Best Answer-推荐答案


这是我的解决方案:

UIWebViewDelegate 函数 webViewDidFinishLoad 中,我们需要将 window.print 函数“重定向”到我们将负责打印的 native 函数:

open func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.stringByEvaluatingJavaScript(from: "(function(){var originalPrintFn = window.print;window.print = function(){window.location = 'webViewPrintAction';}})();")
}

下一步:

public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
   if request.url!.absoluteString.contains("webViewPrintAction") {
            printContent()
            return false
        }
   return true
}

最后一步实现printContent()函数:

private func printContent() {
   let printInfo = UIPrintInfo(dictionary: nil)
   printInfo.jobName = webView.description
   printInfo.outputType = .general

   let printController = UIPrintInteractionController.shared
   printController.printInfo = printInfo
   printController.printingItem = webView
   printController.present(animated: true)
}

现在,当我们在 webView 中按 print 时(第一张截图),我们将看到 iOS 原生对话框(第二张截图):

enter image description here

enter image description here

关于ios - 如何从 UIWebView 打印内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842965/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4