我有一个加密的PDF表单文档,需要在表单中填写所需的值,最后需要保存文档 这是我尝试过的代码
PDDocument document;
document = PDDocument.load(sourcePath);
if( document.isEncrypted() )
{
try
{
document.decrypt( "" );
}
catch( InvalidPasswordException e )
{
}
}
PDAcroForm form = document.getDocumentCatalog().getAcroForm();
PDField Field_1= form.getField("topmostSubform[0].CMS1500Form[0].PatientName[0]");
Field_1.setValue("ABC");
document.save("C:\\Users\\347702\\Desktop\\21.pdf");
document.close();
但它引发了我以下异常
java.lang.NullPointerException at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.prepareDocumentForEncryption(StandardSecurityHandler.java:303)
我还尝试在 doc.save(""); 上方添加以下语句
document.setAllSecurityToBeRemoved(true);
现在我可以执行程序,没有任何错误,但所需的值(值:“ABC”)未填写在保存的文档中..它看起来是空白的
谁能帮帮我!!
谢谢
最佳答案
我查看了 StandardSecurityHandler.java 的代码,即 here 。在这个方法中,我们看到以下代码:
version = computeVersionNumber();
revision = computeRevisionNumber();
encryptionDictionary.setFilter(FILTER);
encryptionDictionary.setVersion(version);
encryptionDictionary.setRevision(revision);
encryptionDictionary.setLength(keyLength);
String ownerPassword = policy.getOwnerPassword();
String userPassword = policy.getUserPassword();
考虑到我们正在查看的版本可能与您的版本不同,最可能的原因是策略对象为 null(这是第 305 行,而不是第 303 行,但这是此后的第一行,可能因 NullPointerException 而失败。
现在,对于未填写的表单字段,您应该不加密地保存并查找字符串 (PatientName[0])
,它应该是您要编辑的字段的字段名称。如果找到它,您应该检查字典是否包含键 /V
以及关联值 (ABC)
,这意味着代码正确设置了该字段。如果是这种情况,我敢打赌你的文档中也有XFA,这意味着表单的实际数据可能不一定存储在表单中,但可能还需要存储在XFA数据包中。好消息是 Adobe 提供了 XFA 规范。坏消息是 XFA 规范有 1500 页。好消息是 XFA 是一个大型 XML 节点套件,具有可下载模式。坏消息是模式不是典型的标准格式,并且使用它的可用工具(显然)没有维护。
关于java - PDFBox : NullPointerException in StandardSecurityHandler. java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837312/