pdfbox "isEncrypted" API 没有给出预期的结果

pdfbox "isEncrypted" API is not giving desired results

这是我的代码,用于了解我正在阅读的 PDF 是否受密码保护:

public static boolean isPasswordProtected(File document)
{
    boolean ret = false;
    try {
        PDDocument originalPdfDoc = PDDocument.load(document);
        ret = originalPdfDoc.isEncrypted();     
        originalPdfDoc.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }           
    return ret;
}

但对于某些 PDF,尽管它们不受密码保护,但仍会返回 true。这是了解 pdf 是否受密码保护的正确方法吗?

这取决于您需要了解什么。一些 PDF 文件使用空用户密码加密,如果这些文件具有受限权限,则可以这样做。如果你想接受这些,你应该尝试用 openProtection():

解锁它们
doc.openProtection(new StandardDecryptionMaterial(""));

并且仅当失败(出现 CryptographyException)时,return 为真。

(此答案仅适用于 1.8.*)

另见此处: How to distinguish between two encrypted / secured PDF files