我目前正在研究 pdfbox 并尝试以编程方式确定字段的可能值,同时枚举 pdf 文档中的所有 PDField。在另一个 post 中,用户推荐了一个带有 acroForm.getField("Nameoffield").getOnValues() 的解决方案,但是类 PDField 中没有定义方法“getOnValues()”,该方法由 acroForm.getField(string ).有没有办法访问实际值并因此设置(例如)随机值?
我目前的尝试围绕着尝试访问所述 getOnValues() 方法,该方法仅为 PDButton 定义。我尝试加载一份政府文件的 pdf 文件,其中包含许多具有各自名称和值的字段,并尝试随机选择其中一个值,但类和方法似乎不允许访问 PDButton 的可能值。
public static void main (String args[]) throws IOException {
// Creating PDF document object
PDDocument document = new PDDocument();
File file = new File("government_form.pdf");
PDDocument formular = PDDocument.load(file);
PDDocumentCatalog pdCatalog = formular.getDocumentCatalog();
PDAcroForm pdAcroForm = pdCatalog.getAcroForm();
// get all fields in form
List<PDField> fields = pdAcroForm.getFields();
System.out.println(fields.size() + " top-level fields were found on the form");
for (PDField field : fields) {
if (!(field instanceof PDNonTerminalField)) {
switch (field.getClass().getName()){
case "org.apache.pdfbox.pdmodel.interactive.form.PDCheckBox":
String fieldname = field.getPartialName();
Set<String> OnValues = new HashSet<String>();
(PDCheckBox)field.getOnValues();
PDCheckBox Checkbox = new PDCheckBox(pdAcroForm);
}
}
}
formular.save("C:/PdfBox_Examples/Formular_ausgefüllt.pdf");
formular.close();
}