我正在尝试使用以下代码下载 PDF 文件:
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + conn.getResponseCode() + " "
+ conn.getResponseMessage();
}
//Useful to display progress
int fileLength = conn.getContentLength();
//Download the mFile
InputStream input = new BufferedInputStream(conn.getInputStream());
//Create a temp file cf. https://developer.android.com/training/data-storage/files.html
// mFile = File.createTempFile(FILENAME, "pdf", mContext.getCacheDir());
mFile = new File(getFilesDir(), "temp.pdf");
FileOutputStream fos = openFileOutput("temp.pdf",MODE_PRIVATE);
byte[] buffer = new byte[10240];
long total = 0;
int count;
while ((count = input.read(buffer)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
//Publish the progress
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
fos.write(buffer);
}
Log.i(LOG_TAG, "File path: " + mFile.getPath());
fos.flush();
fos.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
接下来,我想使用 PdfRenderer 渲染下载的文件。每次我将使用上述代码创建的 File 对象从 PdfRenderer 类传递给 ParcelFileDescriptor.open() 时,我都会收到“异常:文件不是 PDF 格式或已损坏”。
渲染代码对接收到的 File 对象执行以下操作以创建 PdfRenderer:
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
mPdfRenderer = new PdfRenderer(mFileDescriptor);
我该如何解决这个问题?我尝试了许多选项,例如使用 createTempFile 和许多 StackOverFlow 帖子创建临时文件,但我尝试的所有方法都失败了。有谁知道我的问题是由什么引起的?