A PDF can be encrypted in different ways. The most common way is by adding one or two passwords:
- An owner password: everyone can open the PDF, but there might be permissions in place.
- A user password: only people who know either the user password or the owner password can open the document.
If there's a user password in place, iText can't open the document, and a BadPasswordException will be thrown:
public static boolean isPasswordProtected(string file) {
try {
PdfReader pdfReader = new PdfReader(file);
return false;
} catch (BadPasswordException bpe) {
return true;
}
}
If there's only an owner password in place, then you can ignore that password by setting a special parameter. See Can I use iText to merge PDF's with Permissions
PdfReader.unethicalreading = true;
Note that PdfReader also has an isEncrypted() method, see the PageInformation example in chapter 6 of "iText in Action - Second Edition."
This answers the first part of your question: how can I check if a PDF is encrypted or not?
As for the permissions: once you've opened a password protected PDF, you can use the getPermissions() method to know which permissions are in place:
PdfReader pdfReader = new PdfReader(file);
int permissions = pdfReader.getPermissions();
This int is actually a bitset. The PdfEncryptor class has a method getPermissionsVerbose() that explains what each bit means:
public static String More ...getPermissionsVerbose(int permissions) {
StringBuffer buf = new StringBuffer("Allowed:");
if ((PdfWriter.ALLOW_PRINTING & permissions) == PdfWriter.ALLOW_PRINTING) buf.append(" Printing");
if ((PdfWriter.ALLOW_MODIFY_CONTENTS & permissions) == PdfWriter.ALLOW_MODIFY_CONTENTS) buf.append(" Modify contents");
if ((PdfWriter.ALLOW_COPY & permissions) == PdfWriter.ALLOW_COPY) buf.append(" Copy");
if ((PdfWriter.ALLOW_MODIFY_ANNOTATIONS & permissions) == PdfWriter.ALLOW_MODIFY_ANNOTATIONS) buf.append(" Modify annotations");
if ((PdfWriter.ALLOW_FILL_IN & permissions) == PdfWriter.ALLOW_FILL_IN) buf.append(" Fill in");
if ((PdfWriter.ALLOW_SCREENREADERS & permissions) == PdfWriter.ALLOW_SCREENREADERS) buf.append(" Screen readers");
if ((PdfWriter.ALLOW_ASSEMBLY & permissions) == PdfWriter.ALLOW_ASSEMBLY) buf.append(" Assembly");
if ((PdfWriter.ALLOW_DEGRADED_PRINTING & permissions) == PdfWriter.ALLOW_DEGRADED_PRINTING) buf.append(" Degraded printing");
return buf.toString();
}
For instance, if you want to know if assembly is allowed, you need to check the value of PdfWriter.ALLOW_ASSEMBLY & permissions.