下载HTML5/Javascript MOBILE应用程序中的PDF文件

Download PDF file in HTML5/Javascript MOBILE application

本文关键字:PDF 文件 应用程序 MOBILE HTML5 Javascript 下载      更新时间:2023-09-26

我需要创建允许用户从基于HTML5/JavaScript的移动应用程序下载PDF文件的功能。我将得到PDF文件作为一个基地64编码字节流。我如何允许用户在点击页面中的按钮后将PDF下载到他们的设备?

对于IOS:您可以在iPhone应用程序上下载pdf并在WebView中显示。在这个(链接的)问题中列出了一些方法。你还可以在那里找到如何将pdf放在运行应用程序的设备/iPhone的文件夹中:如何下载pdf并将其本地存储在iPhone上?

let request = URLRequest(url:  URL(string: "http://www.msy.com.au/Parts/PARTS.pdf")!)
let config = URLSessionConfiguration.default
let session =  URLSession(configuration: config)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
    if error == nil{
        if let pdfData = data {
            let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("'(filename).pdf")
            do {
                try pdfData.write(to: pathURL, options: .atomic)
            }catch{
                print("Error while writting")
            }
            DispatchQueue.main.async {
                self.webView.delegate = self
                self.webView.scalesPageToFit = true
                self.webView.loadRequest(URLRequest(url: pathURL))
            }
        }
    }else{
        print(error?.localizedDescription ?? "")
    }
}); task.resume()

对于Android:Android有很多方法可以做到这一点。这个应该在大多数情况下工作,没有任何问题:

 URL u = new URL("http://www.path.to/a.pdf");
    //open a connection
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    FileOutputStream f = new FileOutputStream(new File(root,"file.pdf"));
    //read the file
    InputStream in = c.getInputStream();
    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ( (len1 = in.read(buffer)) > 0 ) {
         f.write(buffer,0, len1);
    }
    f.close();

另一个单行选项可以在android中下载pdf,但似乎根据设备和其他安装的应用程序(pdf阅读器)有不同的行为:

`startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("path/filename.pdf")));`

我使用了这个问题和它的回答来获得一个工作代码示例。你可以在文章的底部找到一个很长的答案,在同一篇文章中解释了许多不同的用例及其解决方案如何在Android中下载pdf文件?