ios - 如何从 UIWebView 打印内容?
<p><p>我正在使用 swift,我需要打印在 UIWebView 中打开的工作表。</p>
<pre><code> 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)
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是我的解决方案:</p>
<p>在 <code>UIWebViewDelegate</code> 函数 <code>webViewDidFinishLoad</code> 中,我们需要将 <code>window.print</code> 函数“重定向”到我们将负责打印的 native 函数: </p>
<pre><code>open func webViewDidFinishLoad(_ webView: UIWebView) {
webView.stringByEvaluatingJavaScript(from: "(function(){var originalPrintFn = window.print;window.print = function(){window.location = 'webViewPrintAction';}})();")
}
</code></pre>
<p>下一步:</p>
<pre><code>public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url!.absoluteString.contains("webViewPrintAction") {
printContent()
return false
}
return true
}
</code></pre>
<p>最后一步实现<code>printContent()</code>函数:</p>
<pre><code>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)
}
</code></pre>
<p>现在,当我们在 webView 中按 <code>print</code> 时(第一张截图),我们将看到 iOS 原生对话框(第二张截图):</p>
<p> <a href="/image/RoRDF.png" rel="noreferrer noopener nofollow"><img src="/image/RoRDF.png" alt="enter image description here"/></a> </p>
<p> <a href="/image/8uddb.png" rel="noreferrer noopener nofollow"><img src="/image/8uddb.png" alt="enter image description here"/></a> </p></p>
<p style="font-size: 20px;">关于ios - 如何从 UIWebView 打印内容?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47842965/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47842965/
</a>
</p>
页:
[1]