javascript - 下载在 WKWebView 中加载的嵌入式 PDF

标签 javascript ios swift wkwebview

从 url 加载 HTML5 页面时,我在该页面的某处获取 pdf,我必须下载该 pdf 或将其保存为 base64

这是 pdf 在 HTML 代码中的位置。我不能简单地点击“src”URL 并获取 pdf。

< embed width="100%" height="100%" name="plugin" id="plugin" src="https://myurl.com/fileToOpen.pdf” type="application/pdf" internalinstanceid="8" title="">

任何可以帮助我获取 base64 字符串或任何其他下载方法的 JS?

最佳答案

这个问题有时会反问, 但是,如果有人在使用 WKWebView 寻找 swift 解决方案来下载 .pdf 或文件管理器上的任何文件,这就是我最终的结果

class WebPortalVC: UIViewController, WKNavigationDelegate,WKUIDelegate, UIDocumentInteractionControllerDelegate,URLSessionDownloadDelegate {

覆盖以下函数,它将拦截 url,在我们的例子中,我们检查以 .pdf 和 .csv 结尾的 ulr 并重定向以使用文件管理器 View 打开。可以查看文件、下载并保存在设备存储空间、空投或与其他应用程序共享

只需添加以下功能并检查即可。

 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if let url = navigationAction.request.url {

        print("fileDownload: check ::  \(url)")

        let extention = "\(url)".suffix(4)

        if extention == ".pdf" ||  extention == ".csv"{
            print("fileDownload: redirect to download events. \(extention)")
            DispatchQueue.main.async {
                self.downloadPDF(tempUrl: "\(url)")
            }
            decisionHandler(.cancel)
            return
        }

    }

    decisionHandler(.allow)
}

func downloadPDF(tempUrl:String){
    print("fileDownload: downloadPDF")
    guard let url = URL(string: tempUrl) else { return }
    let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
    let downloadTask = urlSession.downloadTask(with: url)
    downloadTask.resume()
    //showHUD(isShowBackground: true); //show progress if you need
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    print("fileDownload: documentInteractionControllerViewControllerForPreview")
    return self
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // create destination URL with the original pdf name
    print("fileDownload: urlSession")
    guard let url = downloadTask.originalRequest?.url else { return }
    print("fileDownload: urlSession \(url)")
    let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)
    // delete original copy
    try? FileManager.default.removeItem(at: destinationURL)
    // copy from temp to Document
    do {
        try FileManager.default.copyItem(at: location, to: destinationURL)
        myViewDocumentsmethod(PdfUrl:destinationURL)
        print("fileDownload: downloadLocation", destinationURL)
        DispatchQueue.main.async {
            NBMaterialToast.showWithText(self.view, text: "Download Completed", duration: NBLunchDuration.long)
        }
    } catch let error {
        print("fileDownload: error \(error.localizedDescription)")
    }
   // dismissHUD(isAnimated: false); //dismiss progress
}
func myViewDocumentsmethod(PdfUrl:URL){
    print("fileDownload: myViewDocumentsmethod \(PdfUrl)")
    DispatchQueue.main.async {
        let controladorDoc = UIDocumentInteractionController(url: PdfUrl)
        controladorDoc.delegate = self
        controladorDoc.presentPreview(animated: true)
    }
}

关于javascript - 下载在 WKWebView 中加载的嵌入式 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587958/

相关文章:

javascript - DOMParser 在 IE9 中未定义

iphone - 为字符串返回 null

ios - 在函数中初始化之前使用的变量

ios - 在 Swift 中使用 SRWebClient 上传多张图片

ios - 如何在 SwiftUI 中更改每个 View 的状态栏文本颜色?

javascript - fetch => response.json() 请求被拒绝

javascript - 如何在 jquery 中访问内部 span 标签

javascript - 使用 JavaScript/html;如何在打印区域之外打印 Canvas ?

ios - 如何在 iOS 中实现延迟深度链接

ios - 二元运算符 ..< 不能应用于操作数 'Int' 和 'Int?'