How to render PDF file from Internal storage inside Android App using PdfRenderer

by Ayan Bhattacharjee   Last Updated August 01, 2020 14:26 PM

I am trying to give a preview of PDF to the user before uploading it to a server. I am using PdfRenderer. I just to give the preview of the 1st page. On Start, I am calling the file chooser function that lets you select a pdf file from Internal memory, and on ActivityResult the render function is called, however, I am facing an error

I/System.out: Cursor= [email protected]
    Uri String= content://com.adobe.scan.android.documents/document/root%3A23
    File pathcontent://com.adobe.scan.android.documents/document/root%3A23
W/System.err: java.lang.IllegalArgumentException: Invalid page index
        at android.graphics.pdf.PdfRenderer.throwIfPageNotInDocument(PdfRenderer.java:282)
        at android.graphics.pdf.PdfRenderer.openPage(PdfRenderer.java:229)
        at com.ay404.androidfileloaderreader.CustomFunc.Main2Activity.openPdfFromStorage(Main2Activity.java:56)

Here is my code:

  @RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
        private void openPdfFromStorage(Uri uri,String filename) throws IOException {
            File fileCopy = new File(getCacheDir(), filename);//anything as the name
            copyToCache(fileCopy, uri);
            ParcelFileDescriptor fileDescriptor =
                    ParcelFileDescriptor.open(fileCopy,
                            ParcelFileDescriptor.MODE_READ_ONLY);
            mPdfRenderer = new PdfRenderer(fileDescriptor);
            mPdfPage = mPdfRenderer.openPage(1);
             Bitmap bitmap = Bitmap.createBitmap(mPdfPage.getWidth(),
                    mPdfPage.getHeight(),
                    Bitmap.Config.ARGB_8888);//Not RGB, but ARGB
            mPdfPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            imageView.setImageBitmap(bitmap);
        }

void copyToCache(File file,Uri uri) throws IOException {
        if (!file.exists()) {

            InputStream input = getContentResolver().openInputStream(uri);
            FileOutputStream output = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int size;

            while ((size = input.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }

            input.close();
            output.close();
        }
    }
RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            Uri uri = data.getData();
            String uriString=uri.toString();
            File myFile=new File(uriString);
            String displayName=null;
            Cursor cursor=null;
            Log.e("URI: ", uri.toString());
            try {

                if (uriString.startsWith("content://")) {

                    try {
                        cursor=getApplicationContext().getContentResolver().query(uri, null, null, null, null);
                        System.out.println("Cursor= " + cursor);
                        System.out.println("Uri String= " + uriString);
                        System.out.println("File path" + data.getData());

                        if (cursor != null && cursor.moveToFirst()) {
                            displayName=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                            openPdfFromStorage(uri,displayName);
                            File imgFile=new File(String.valueOf(data.getData()));

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        cursor.close();
                    }
                } else if (uriString.startsWith("file://")) {

                    System.out.println("Uri String= " + uriString);
                    System.out.println("File path" + myFile.getAbsolutePath());
                    displayName=myFile.getName();
                    try {
                        openPdfFromStorage(uri,displayName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void fileChoser(){
        Intent intent=new Intent();
        intent.setType("application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
    }

    @Override
    protected void onStart() {
        super.onStart();
        fileChoser();
    }
}


Related Questions


Downloading a PDF from threejs visualizer

Updated March 27, 2018 16:26 PM

CGContextDrawPDFPage memory Leak - App Crash

Updated October 24, 2017 06:26 AM