【问题标题】:How to take PRINT of content from UIWebView?如何从 UIWebView 打印内容?
【发布时间】:2017-12-16 05:53:20
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: ios swift3 uiwebview uiprintinteractioncntrler


    【解决方案1】:

    这是我的解决方案:

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

    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 原生对话框(第二张截图):

    【讨论】:

    • 我认为这行不通。printingItem 只能接受 NSURL、NSData、UIImage 或 ALAsset。它不接受 UIView。
    【解决方案2】:

    通过创建图像上下文,然后在 Web 视图上调用 drawHierarchy(in:afterScreenUpdates:) 方法,将 Web 视图的内容绘制到 UIImage

    然后您可以将生成的图像作为printingItem 传递给您的打印交互控制器。

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多