下载 WKWebView 中加载的嵌入 PDF [英] Download embedded PDF loaded in WKWebView
问题描述
从 url 加载 HTML5
页面时,我在该页面的某处获取 pdf,我必须下载该 pdf 或将其另存为 base64
.
While loading HTML5
page from url I'm getting pdf somewhere in that page and I have to download that pdf or save it as base64
.
这是 pdf 在 HTML 代码中的位置.我不能简单地点击src" URL 并获取 pdf.
This is where the pdf is in the HTML code. I cannot simply hit the 'src' URL and get the pdf.
< embed width="100%" height="100%" name="plugin" id="plugin" src="https://myurl.com/fileToOpen.pdf" type="application/pdf" internalinstanceid="8" title="">
任何可以帮助我获取 base64
字符串的 JS 或任何其他下载方法?
Any JS which can help me get base64
string of that or any other method to download?
推荐答案
更新
来自 文档 他们说
Fetch API 提供了一个用于获取资源的接口(包括通过网络).用过的人都会觉得很熟悉XMLHttpRequest
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest
您也可以使用以下字符串从 WKWebview 中获取 base64 字符串
You can also use the following string to get the base64 String from the WKWebview
let s = "path = document.getElementById(\"plugin\").src\n" +
"\n" +
"fetch(path).then(function (response) {\n" +
" response.body.getReader().read().then(function(result) {\n" +
" return btoa(String.fromCharCode.apply(null, result.value));\n" +
" }).then(function(b64) {\n" +
" window.webkit.messageHandlers.myInterface.postMessage(b64);\n" +
" });\n" +
"});"
fetch 和 xmlhttp 都是异步工作的.. 你需要做的就是等待处理完成后使用 javascript 的 ios 桥(WKScriptMessageHandler)将它传递给 Swift
使用以下代码将 base64 字符串从 javascript 获取到 Swift.当 base64 字符串为准备消费.在 String 中,您只需要传递 pdf 的 url,它就会执行 ajax 请求以获取 pdf 文件,然后将其转换为 base64 字符串.
both fetch and xmlhttp works async.. all you need to do is wait when the processing gets completed pass it to the Swift using javascript's bridge to ios (WKScriptMessageHandler)
Use the following code to get the base64 string from javascript to Swift. I am using WKScriptMessageHandler to get the callback from Javascript when the base64 string is ready to be consumed. In the String s you just need to pass the url of the pdf and it will do a ajax request to get the pdf file and then convert it to base64 string.
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var btnPDF: UIButton!
@IBOutlet weak var webViewParentView: UIView!
var activityIndicator: UIActivityIndicatorView?
var webView: WKWebView!
@objc func didSelect(_ sender: UIView){
let s="var xhr = new XMLHttpRequest();\n" +
"xhr.open(\'GET\', \"https://codingexceptions.com/wkwebview/dummy.pdf\", true);\n" +
"\n" +
"xhr.responseType = \'arraybuffer\';\n" +
"\n" +
"xhr.onload = function(e) {\n" +
" if (this.status == 200) {\n" +
" var uInt8Array = new Uint8Array(this.response);\n" +
" var i = uInt8Array.length;\n" +
" var binaryString = new Array(i);\n" +
" while (i--)\n" +
" {\n" +
" binaryString[i] = String.fromCharCode(uInt8Array[i]);\n" +
" }\n" +
" var data = binaryString.join(\'\');\n" +
"\n" +
" var base64 = window.btoa(data);\n" +
"\n" +
"window.webkit.messageHandlers.myInterface.postMessage(base64);" +
"\n" +
" }\n" +
"};\n" +
"\n" +
"xhr.send();\n"
webView.configuration.userContentController.add(self, name: "myInterface")
webView?.evaluateJavaScript(s, completionHandler: {(string,error) in
print(error ?? "no error")
})
}
func setupWebView(){
webView = WKWebView.init(frame: CGRect(x: 0, y: 0, width: webViewParentView.frame.width, height: webViewParentView.frame.height))
webView.navigationDelegate = self
webViewParentView.addSubview(webView)
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator?.center = self.view.center
self.view.addSubview(activityIndicator!)
webView.load(URLRequest(url: URL(string: "https://codingexceptions.com/wkwebview/index.php")!))
activityIndicator?.startAnimating()
}
override func viewDidLoad() {
super.viewDidLoad()
btnPDF.addTarget(self, action: #selector(self.didSelect(_:)), for: .touchUpInside)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupWebView()
}
}
extension ViewController: WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("Message received: \(message.name) with body: \(message.body)")
}
}
extension ViewController: WKNavigationDelegate{
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.activityIndicator?.stopAnimating()
self.activityIndicator?.removeFromSuperview()
self.activityIndicator = nil
}
}
更新:从@Tarun 的回答中指出的嵌入标签中获取源
Update: To get the source from the embed tag as pointed in @Tarun's answer
只需将下面的行放在字符串变量 s 的开头 并在 xhr.open 中传递 url
just put the below line in the starting of string variable s and pass the url in xhr.open
var url = document.getElementById("plugin").src
这篇关于下载 WKWebView 中加载的嵌入 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!