我正在使用PDFBox来确定pdf文件是否受密码保护。这是我的代码:
boolean isProtected = pdfDocument.isEncrypted();
我的文件属性在截图中。在这里我得到isProtected= true
即使我可以打开它没有密码。
注意:此文件具有文档打开密码:否和权限密码:是。
您的PDF有一个空的用户密码和一个非空的所有者密码。是的,它是加密的。这样做是为了防止人们做某些事情,例如内容复制。
这不是真正的安全;查看器软件有责任注意不允许“禁止”操作。
你可以找到更长的(并且有点有趣)解释here。
要查看文档访问权限,请使用PDDocument.getCurrentAccessPermission()
。
在2.0。*中,如果此调用成功,用户将能够查看文件:
PDDocument doc = PDDocument.load(file);
如果抛出InvalidPasswordException
,则表示需要非空密码。
我发布这个答案是因为Stack Overflow和Web上的其他地方你可能会看到建议的方法来检查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而无需密码。