PDFBox returns isEncrypted true 即使我可以打开文件

PDFBox returns isEncrypted true even if i can open file

我正在使用 PDFBox 来确定 pdf 文件是否受密码保护。 这是我的代码:

boolean isProtected = pdfDocument.isEncrypted();

我的文件属性在截图中。 在这里我得到 isProtected= true 即使我可以在没有密码的情况下打开它。

注意:此文件的文档打开密码:否和权限密码:是。

您的 PDF 有一个空的用户密码和一个非空的所有者密码。是的,它是加密的。这样做是为了防止人们做某些事情,例如内容复制。

这不是真正的证券;查看器软件有责任注意不允许 "forbidden" 操作。

您可以找到更长(并且有点有趣)的解释 here

要查看文档访问权限,请使用 PDDocument.getCurrentAccessPermission()

在 2.0.* 中,如果此调用成功,用户将能够查看文件:

PDDocument doc = PDDocument.load(file);

如果抛出 InvalidPasswordException,则表示需要非空密码。

我发布这个答案是因为在 Stack Overflow 和网络的其他地方,您可能会看到在 PDFBox 中检查受密码保护的 PDF 的建议方法是使用 PDDocument#isEncrypted()。我们发现的问题是某些未提示输入密码的 PDF 仍被标记为已加密。有关为什么会发生这种情况的一种解释,请参阅已接受的答案,但无论如何我们都使用以下模式作为解决方法:

boolean isPDFReadable(byte[] fileContent) {
    PDDocument doc = null;
    try {
        doc = PDDocument.load(fileContent);
        doc.getPages();  // perhaps not necessary
        return true;
    }
    catch (InvalidPasswordException invalidPasswordException) {
        LOGGER.error("Unable to read password protected PDF.", invalidPasswordException);
    }
    catch (IOException io) {
        LOGGER.error("An error occurred while reading a PDF attachment during account submission.", io);
    }
    finally {
        if (!Objects.isNull(doc)) {
            try {
                doc.close();
                return true;
            }
            catch (IOException io) {
                LOGGER.error("An error occurred while closing a PDF attachment ", io);
            }
        }
    }

    return false;
}

如果对 PDDocument#getPages() 的调用成功,那么这也意味着应该可以通过双击或浏览器打开 PDF,无需密码。