How to take PRINT of content from UIWebView?

坚强是说给别人听的谎言 提交于 2019-12-24 02:31:46

问题


I am using swift, i need to take print of a sheet which is opened in 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)

回答1:


Here is my solution:

in UIWebViewDelegate in function webViewDidFinishLoad we need to "redirect" window.print function to our native function that will take care of print:

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

next step:

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

and final step inmplement printContent() function:

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)
}

And now when we will press print in webView (1st screenshot) we will see iOS native dialog (2nd screenshot):




回答2:


Draw the contents of the web view to a UIImage by creating an image context and then calling the drawHierarchy(in:afterScreenUpdates:) method on the web view.

You can then pass the resulting image as the printingItem to your print interaction controller.



来源:https://stackoverflow.com/questions/47842965/how-to-take-print-of-content-from-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!