Alessandro Falappa
Alessandro Falappa

Reputation: 303

How to read the permissions of an encrypted PDF file?

I am reading PDF files with iText v7 and I am detecting encrypted files as follows:

try (final PdfReader pdfReader = new PdfReader(file.getAbsolutePath())) {
     PdfDocument document = new PdfDocument(pdfReader);
    System.out.println("encrypted = " + pdfReader.isEncrypted());
}

I would like to know which individual permissions are allowed on the PDF files (printing, copy text, modify content, modify annotations).

I know that the getPermissions method should return the permissions read from the file but I haven't managed to check the relevant flags, i.e. the following code does not yeld the correct results:

final long perm = - pdfReader.getPermissions();
if ((perm & EncryptionConstants.ALLOW_PRINTING) == EncryptionConstants.ALLOW_PRINTING) {
    System.out.println("Allow printing");
}

The documentation I have found is a bit terse on the subject, mainly detailng how to create an encrypted file with specific permissions.

Upvotes: 1

Views: 1041

Answers (1)

Alessandro Falappa
Alessandro Falappa

Reputation: 303

Answering my own question, inspired by the answer to this question.

Use the PdfEncryptor class to decode the permission flags packed in the long returned by PdfReader.getPermissions method:

final int perm = (int) pdfReader.getPermissions();
if (PdfEncryptor.isDegradedPrintingAllowed(perm)) {
    System.out.println("Allow degraded printing";
}

The only anomaly found in the API is that getPermissions returns long while the PdfEncryptor methods take int as an argument.

Upvotes: 1

Related Questions