Reputation: 1982
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).
Upvotes: 2
Views: 1393
Reputation: 3316
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();
}
}
Upvotes: 1