SecurityException with PdfRenderer, comes with password protected pdfs, and than repeats even with normal pdfs

1.1k Views Asked by At

If trying to open Password Protected PDF with PdfRenderer API, gives SecurityException and handled accordingly, inside catch block and thenonDestroy basic clean up is done, and comes back to home activity and then navigating a simple non-protected PDF than again the same exception occurs.

Please note, this happens only once any protected file got opened.

Refer below code:

      @Override
    protected PdfRenderer doInBackground(Uri... uri) {
        Uri uriToProcess = uri[0];
        try {
            contentResolver=getContentResolver();
            parcelFileDescriptor = contentResolver.openFileDescriptor(uriToProcess, "r");
            if(parcelFileDescriptor!=null && mPdfRenderer==null) {
                mPdfRenderer = new PdfRenderer(parcelFileDescriptor);
            }
        } catch (FileNotFoundException e) {
            exceptionMsg="Sorry! No such file or directory found";
            handleExceptionInUI(exceptionMsg, progressDialog);
            Log.e("$$$$ FNFException", e.toString());

        } catch (IOException e) {
            exceptionMsg="Sorry! Something went wrong with IO";
            handleExceptionInUI(exceptionMsg, progressDialog);
            Log.e("$$$$ IOException", e.toString());
        } catch (SecurityException e) {
            if (parcelFileDescriptor!=null) {
                try {
                    parcelFileDescriptor.close();
                    parcelFileDescriptor = null;
                    contentResolver=null;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            if (mPdfRenderer!=null){
                mPdfRenderer.close();
                mPdfRenderer=null;
            }

            exceptionMsg="Password protected file, This can't be opened";
            handleExceptionInUI(exceptionMsg, progressDialog);
            Log.e("$$$$ SecurityException", e.toString());
        } catch (Exception e) {
            exceptionMsg="Sorry! Something went wrong.";
            handleExceptionInUI(exceptionMsg, progressDialog);
            Log.e("$$$$ EXCEPTION", e.toString());
        }
        return mPdfRenderer;
    }

Any help cordially appreciated.

1

There are 1 best solutions below

0
On

I had the same problem with my app. The way I solved it was using an https://github.com/TomRoush/PdfBox-Android and load the document and check for password protection. After no InvalidPasswordException has been thrown the file can be safely loaded with the PdfRenderer.