【发布时间】:2017-12-24 13:47:33
【问题描述】:
我正在尝试使用以下代码下载 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 帖子创建临时文件,但我尝试的所有方法都失败了。有谁知道我的问题是由什么引起的?
【问题讨论】:
-
我建议您尝试 MuPDF,不过这是我的意见。当我上次使用 PDF 渲染器时,它也遇到了一些文件和大文件的奇怪问题,但使用 MuPDF,到目前为止还不错
-
首先,请注意
PdfRenderer不能渲染任意PDF文件。它仅用于打印预览。使用FileProvider并允许用户在他们首选的 PDF 阅读器中查看文档。或者,使用other PDF rendering options。除此之外,请注意您正在下载到标识为mFile的File,但您的ParcelFileDescriptor.open()调用使用的是file。也许mFile和file没有指向同一个位置。 -
@CoolGuyCG 你用 NDK 编译过 MuPDF 吗?据我所知,将 MuPDF 源代码应用于 Android 应用程序需要做很多工作。我错了吗?
-
是的,请,这似乎是很多工作,但如果您按照给出的说明进行操作,这很容易
标签: android pdfrenderer