如何从Internet下载PDF文件并使用PdfRenderer进行渲染

时间:2017-12-24 13:47:34

标签: android pdfrenderer

我正在尝试使用以下代码下载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帖子创建临时文件,但我尝试过的都失败了。有谁知道我的问题是由什么造成的?

1 个答案:

答案 0 :(得分:0)

首先,您需要在Android中创建一个文件并打开输出文件流:

        mFile = new File(getFilesDir(), "temp.pdf");
        FileOutputStream fos = openFileOutput("temp.pdf",MODE_PRIVATE);

接下来,在写入输出流时,您需要避免一个非常常见的Java故障(由this post提供)并将流编写器更改为:

            fos.write(buffer, 0, count);