问题
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