Reputation: 79
I need to check if the PDF has the following properties before uploading PDF process starts,
1) PDF should not be password protected 2) PDF should not have the Document Properties - Page Extraction & Content Copying & Content Copying for Accessibility NOT ALLOWED.
I'm able to check whether the PDF is password protected or not using PdfReader IsEncrypted property. But when the PDF has no Security Method set, how can I check the above mentioned document properties. Permissions is useful only when the document is encrypted. (using iTextsharp dll)
Upvotes: 1
Views: 2592
Reputation: 77606
A PDF can be encrypted in different ways. The most common way is by adding one or two passwords:
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
.
Upvotes: 1