使用 iText 设置新创建的复选框的导出值

Set export value of a new created checkbox with iText

我需要在现有 pdf 中添加一个复选框。我还需要设置此复选框的导出值。我看到这应该使用外观字典 /AP 配置,但直到现在我确实评估了如何在新复选框上设置它。 对于导出值,我指的是屏幕截图中标记的值

这是我创建复选框的代码,但导出值始终为空...

case AcroFields.FIELD_TYPE_CHECKBOX:
            PdfFormField checkbox = PdfFormField.createCheckBox(stamper.getWriter());
            checkbox.setWidget(fieldVO.rect, PdfAnnotation.HIGHLIGHT_NONE);
            checkbox.setFieldName(fieldVO.getNewName());
            //TODO set export value
            log.info("exportValue is " + fieldVO.getExportValue());
            stamper.addAnnotation(checkbox, fieldVO.getPageNumber());
            break;

首先:您正在使用 PdfFormField 创建一个复选框。那很难。为什么不用 RadioCheckField class?

rect = new Rectangle(180, 806, 200, 788);
checkbox = new RadioCheckField(stamper.getWriter(), rect,
     "fieldVO.getNewName()", "on");
field = checkbox.getCheckField();

然后你要定义外观。假设 onOff 是一个包含 PdfAppearance 个对象的数组,如果未选中框(0),一个对象具有外观,如果选中框(1),则具有外观.请注意,关闭状态 的名称应为 ISO-32000-1 中定义的 "Off"。据我所知,标准建议对 on 状态 使用 "Yes",但您可以使用自定义值,例如 "MyCustomValue":

field.setAppearance(
    PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]);
field.setAppearance(
    PdfAnnotation.APPEARANCE_NORMAL, "MyCustomValue", onOff[1]);

在这种情况下,on state 的外观将被存储为一个带有键 /MyCustomValue 的条目。此键是一个 PDF 名称对象,并且有一些限制。这就是引入 /Opt 键的原因:

(Taken from ISO-32000-1) Beginning with PDF 1.4, the field dictionary for check boxes and radio buttons may contain an optional Opt entry. If present, the Opt entry shall be an array of text strings representing the export value of each annotation in the field. It may be used for the following purposes:

  • To represent the export values of check box and radio button fields in non-Latin writing systems. Because name objects in the appearance dictionary are limited to PDFDocEncoding, they cannot represent non-Latin text.
  • To allow radio buttons or check boxes to be checked independently, even if they have the same export value.

EXAMPLE: a group of check boxes may be duplicated on more than one page such that the desired behavior is that when a user checks a box, the corresponding boxes on each of the other pages are also checked. In this case, each of the corresponding check boxes is a widget in the Kids array of a check box field.

在你的情况下,你需要这样的东西:

PdfArray options = new PdfArray();
options.add(new PdfString("My Custom Value"));
field.put(PdfName.OPT, options);

我还没有测试这是否有效,我只是在解释 ISO-32000-1 所说的内容并将规范转换为 iText 代码。

终于可以添加字段了。

stamper.addAnnotation(field, 1);