I am using PDFBox for validating a pdf document and one of the validation states that whether the pdf document is printable or not.
I use the following code to perform this operation:
PDDocument document = PDDocument.load("<path_to_pdf_file>");
System.out.println(document.getCurrentAccessPermission().canPrint());
but this is returning me true though when the pdf is opened, it shows the print icon disabled.
Access permissions are integrated into a document by means of encryption.
Even PDF documents which don't ask for a password when opened in Acrobat Reader may be encrypted, they essentially are encrypted using a default password. This is the case in your PDF.
PDFBox determines the permissions of an encrypted PDF only while decrypting it, not already when loading a PDDocument
. Thus, you have to try and decrypt the document before inspecting its properties if it is encrypted.
In your case:
PDDocument document = PDDocument.load("<path_to_pdf_file>");
if (document.isEncrypted())
{
document.decrypt("");
}
System.out.println(document.getCurrentAccessPermission().canPrint());
The empty string ""
represents the default password. If the file is encrypted using a different password, you'll get an exception here. Thus, catch accordingly.
PS: If you do not know all the passwords in question, you may still use PDFBox to check the permissions, but you have to work more low-level:
PDDocument document = PDDocument.load("<path_to_pdf_file>");
if (document.isEncrypted())
{
final int PRINT_BIT = 3;
PDEncryptionDictionary encryptionDictionary = document.getEncryptionDictionary();
int perms = encryptionDictionary.getPermissions();
boolean printAllowed = (perms & (1 << (PRINT_BIT-1))) != 0;
System.out.println("Document encrypted; printing allowed?" + printAllowed);
}
else
{
System.out.println("Document not encrypted; printing allowed? true");
}