英文:
PDFBox invalid option in radio
问题
尝试使用以下代码填充此PDF表单(http://vaielab.com/Test/2.pdf)时,出现了以下错误:
```java
PDDocument pdfDocument = PDDocument.load(new File("2.pdf"));
pdfDocument.setAllSecurityToBeRemoved(true);
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
if (acroForm != null) {
PDField field = (PDField) acroForm.getField("rad2");
try {
field.setValue("0");
} catch (Exception e) {
System.out.println(e);
}
}
pdfDocument.save("output.pdf");
pdfDocument.close();
我收到了这个错误:值“0”不是字段rad2的有效选项,有效值为:[Yes] 和 Off
但是值“0”应该是一个有效选项,如果我使用pdftk进行dump_data_fields,我得到了以下内容:
FieldType: Button
FieldName: rad2
FieldFlags: 49152
FieldJustification: Left
FieldStateOption: 0
FieldStateOption: 1
FieldStateOption: Off
FieldStateOption: Yes
我还尝试了值“1”,但是得到了完全相同的错误。
我正在使用pdfbox 2.0.20
<details>
<summary>英文:</summary>
When trying to fill the form of this pdf (http://vaielab.com/Test/2.pdf) with this code
PDDocument pdfDocument = PDDocument.load(new File("2.pdf"));
pdfDocument.setAllSecurityToBeRemoved(true);
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
if (acroForm != null) {
PDField field = (PDField) acroForm.getField("rad2");
try {
field.setValue("0");
} catch (Exception e) {
System.out.println(e);
}
}
pdfDocument.save("output.pdf");
pdfDocument.close();
I get this error: value '0' is not a valid option for the field rad2, valid values are: [Yes] and Off
But value "0" should be a valid option, and if I do a dump_data_fields with pdftk, I get this:
FieldType: Button
FieldName: rad2
FieldFlags: 49152
FieldJustification: Left
FieldStateOption: 0
FieldStateOption: 1
FieldStateOption: Off
FieldStateOption: Yes
I also tried the value "1" but get the exact same error.
I'm using pdfbox 2.0.20
</details>
# 答案1
**得分**: 2
这是因为在`Root/AcroForm/Fields/[7]/Opt`中的`Opt`值,其中一个只有两个“是”条目。当设置了`/Opt`时,PDFBox中的`PDButton.setValue()`代码会以不同的方式更新此字段。在这种情况下,最好的做法是不进行设置,或通过调用`field.setExportValues(null)`来移除这些条目。然后有效的设置将为0、1和“关闭”。
[![字段的PDFDebugger截图][1]][1]
[1]: https://i.stack.imgur.com/p7jwU.png
<details>
<summary>英文:</summary>
This is because of the `Opt` values in `Root/AcroForm/Fields/[7]/Opt`, that one has two "Yes" entries only. The `PDButton.setValue()` code in PDFBox updates this field differently when `/Opt` is set. The best here would be not to set it, or remove these entries by calling `field.setExportValues(null)` . Then valid settings would be 0, 1 and "Off".
[![PDFDebugger screenshot of the field][1]][1]
[1]: https://i.stack.imgur.com/p7jwU.png
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论