我需要创建允许用户从我的基于 HTML5/JavaScript 的移动应用程序下载 PDF 文件的功能。我将把 PDF 文件作为 Base 64 编码字节流。单击页面中的按钮后,如何允许用户将 PDF 下载到他们的设备?
问问题
6124 次
1 回答
0
对于 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 文件?
于 2020-02-03T13:54:16.333 回答