I am trying to download a PDF file with the following code:
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();
}
Next, I want to render the downloaded file using PdfRenderer. Each time I pass the File object created using the above code to ParcelFileDescriptor.open() from the PdfRenderer class, I receive "Exception: file not in PDF format or corrupted".
The rendering code does the following to the received File object to create a PdfRenderer:
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
mPdfRenderer = new PdfRenderer(mFileDescriptor);
How can I solve this? I have tried many options like creating temporary files with createTempFile and many StackOverFlow posts, but all I tried has failed. Does anyone know what my problem is caused by?