PDFBox not recognising pdf to be non printable

社会主义新天地 提交于 2019-12-11 01:30:27

问题


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.


回答1:


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");
}


来源:https://stackoverflow.com/questions/19882581/pdfbox-not-recognising-pdf-to-be-non-printable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!