【发布时间】:2019-07-17 12:29:22
【问题描述】:
我正在尝试使用权限和密码保护 PDF 文件,然后使用“saveIncremental”方法保存它(因为如果签名在 PDF 文件中,我希望它即使在保护后仍然有效)。
这里是代码sn-p:
StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy(ownerPassword, userPassword, accessPermission);
File protectedFile = new File(pdfFile.getParent(), substring + "_protected.pdf");
try (PDDocument document = PDDocument.load(pdfFile)) {
document.protect(standardProtectionPolicy);
SecurityHandler securityHandler = document.getEncryption().getSecurityHandler();
if (!securityHandler.hasProtectionPolicy()) {
throw new IllegalStateException("PDF contains an encryption dictionary, please remove it with "
+ "setAllSecurityToBeRemoved() or set a protection policy with protect()");
}
securityHandler.prepareDocumentForEncryption(document);
// update and save
document.getDocument().getEncryptionDictionary().setNeedToBeUpdated(true);
document.getEncryption().getCOSDictionary().setNeedToBeUpdated(true);
COSDictionary encrypt = (COSDictionary) document.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.ENCRYPT);
if (encrypt != null) encrypt.setNeedToBeUpdated(true);
document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true);
document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);
document.saveIncremental(new FileOutputStream(protectedFile));
}
我用this file。
Here 是结果 - 受保护的 PDF 文件和“allSecurityToBeRemoved”之后的相同文件。
用户密码为“user”,所有者密码为“owner”。
问题是那个受保护的文件。其内容不可见,签名无效,所有签名信息都以不可读的字符显示...
使用“保存”它可以工作,但不能使用“saveIncremental”。是否可以使用“saveIncremental”使其签名保持有效?如果是,怎么做?
我正在使用 PDFBox 2.0.7 和 Adobe Acrobat Reader DC。
感谢大家的帮助!
【问题讨论】:
-
当然不会... saveIncremental 不会加密现有的 PDF。它只能追加,所以这是一个可怕的混乱。
-
并且当前版本是2.0.16。 (但它也不会在那里工作)
-
@TilmanHausherr 所以在 PDFBox 中没有办法用签名加密文件,所以签名将保持有效?
-
不是增量的。不适用于 PDFBox,也不适用于其他软件。您必须在开始时加密,即在创建 PDF 时。 (或者你正常加密保存,然后重新加载签名,增量保存。