如何在线显示PDF文件,以及下载它并在我的应用程序中查看相同活动的选项



我想制作一个应用程序,显示我使用webview完成的在线服务器(在我的情况下是Google文档(的PDF文件 这里的图像将如何,但如果用户想离线查看它,那么我必须提供下载选项,所以如果他们按下载,我想删除"在线模式"按钮,以便他们可以像这样离线查看它还有一个删除选项,删除下载的文件并保留在线模式请帮助我编写代码我是 android 新手

要在安卓中显示 Pdf 文件,您可以使用此库。您可以在他们的文档中找到它的用法。要下载文件,您可以尝试以这种方式

private class PdfDownloader extends AsyncTask<String, Integer, String> {
byte[] pdfFile;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
try {
URL myURL = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
connection.setDoInput(true);
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Error";
}
InputStream is = connection.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int newLength;
while ((newLength = is.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, newLength);
}
pdfFile = byteArrayOutputStream.toByteArray();
is.close();
return "Success";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}

}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("Success")) {
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(pdfFile);
}
catch (Exception e){
e.printStackTrace();
}
}
}
}

然后使用

new PdfDownloader().execute(PdfFileUrl);

你可以很容易地做到

首先,我建议您将pdf文件存储在Google云端硬盘中,而不是Google文档中。 在此之后,您可以轻松地从谷歌驱动器下载文件。

从谷歌云端硬盘下载文件

[https://stackoverflow.com/a/48824834/13651827][1]

提供离线文件

接下来,根据您的说法,您还希望离线提供pdf文件。为此,首先,您必须下载文件并将其存储在用户设备的存储中。 现在,从设备存储访问pdf文件,并提供给用户,即使用户离线或在线。

最新更新