繁体   English   中英

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

[英]Download PDF file in HTML5/Javascript MOBILE application

我需要创建允许用户从我的基于 HTML5/JavaScript 的移动应用程序下载 PDF 文件的功能。 我将获取 PDF 文件作为 Base 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 文件?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM