简体   繁体   中英

PdfRenderer always throwing 'password required' SecurityException after rendering a password-protected file

I have the following Android code:

private void test() throws IOException {
    File f1 = new File("/sdcard/password-protected-pdf.pdf");
    File f2 = new File("/sdcard/normal-pdf.pdf");

    this.renderPDF(f1);
    this.renderPDF(f2);
}

private void renderPDF(File f) throws IOException {
    PdfRenderer renderer = null;

    try {
        renderer = new PdfRenderer(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY));
    } catch (SecurityException e) {
        e.printStackTrace();
    } finally {
        if (renderer != null)
            renderer.close();
    }
}

The PDF file f1 is password protected. The PDF file f2 is not. When I run the code, both files throw a security exception for some reason ( password required or incorrect password ). When I switch the order ( f2 goes first and f1 second), correctly, only the password protected PDF throws the exception.

Is there something I am doing wrong? Thanks.

EDIT: I am suspecting that it has something to do with the open() method, returning a static object. However I was not able to figure a way to effectively destroy it (I tried close() on the returned ParcelFileDescriptor object with no luck).

I have also faced a similar problem. You can use PDFBox for Android https://github.com/TomRoush/PdfBox-Android and load the document and check for password protection. if fil is secured then it will throw IOException

Note: Using this library will increase your app size.

private void test() throws IOException {
File f1 = new File("/sdcard/password-protected-pdf.pdf");
File f2 = new File("/sdcard/normal-pdf.pdf");

this.renderPDF(f1);
this.renderPDF(f2);
}

private void renderPDF(File f) throws IOException {
PdfRenderer renderer = null;

try {
  // That will throw if document is password protected
    PDDocument.load(f)
    renderer = new PdfRenderer(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY));
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IOException e) {
  // Check for Password
    e.printStackTrace();
} 
 finally {
    if (renderer != null)
        renderer.close();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM