交互式表单

本指南展示了如何使用 Aspose.PDF FOSS 为 Java 创建和管理 PDF 文档中的 AcroForm 字段。您将学习添加单选按钮、复选框、文本字段、组合框和列表框,并检索提交的字段值。

AcroForm API

通过 Document.getForm() 可访问的 Form 类管理文档中所有的 AcroForm 字段。字段可通过调用 Form.add(field, pageNumber) 添加。

RadioButtonField

创建一组单选按钮,每个选项位于其自己的 Rectangle。每个选项使用标签和边界框添加。调用 setValue() 预先选择一个选项:

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    RadioButtonField radio = new RadioButtonField(page);
    radio.setPartialName("color");
    radio.addOption("Red", new Rectangle(50, 50, 70, 70));
    radio.addOption("Blue", new Rectangle(50, 80, 70, 100));
    doc.getForm().add(radio, 1);
    radio.setValue("Red");
    doc.save("form.pdf");
}

setValue() 以编程方式选择一个选项。getValue() 返回当前选中的选项名称。

CheckboxField

CheckboxField 在 PDF 表单中表示单个布尔输入字段。将 setChecked(true) 设置为使该字段默认被选中。将其添加到表单的特定页码(从 1 开始计数):

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    CheckboxField cb = new CheckboxField(page, new Rectangle(100, 100, 120, 120));
    cb.setPartialName("agree");
    cb.setChecked(true);
    doc.getForm().add(cb, 1);
    doc.save("form.pdf");
}

TextBoxField

TextBoxField 接受自由文本输入。使用 setValue() 设置默认值,并在保存前将该字段注册到表单:

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    TextBoxField text = new TextBoxField(page, new Rectangle(50, 200, 250, 220));
    text.setPartialName("name");
    text.setValue("Default text");
    doc.getForm().add(text, 1);
    doc.save("form.pdf");
}

ComboBoxField 和 ListBoxField

ComboBoxField 和 ListBoxField 提供可选项列表。两者都通过 addOption() 接受选项字符串,并公开 getValue() 用于获取所选项。

FormEditor

FormEditor 是用于操作 AcroForm 字段的外观类。使用 bindPdf() 绑定文档,应用更改,然后调用 save()。

读取字段值

加载已填充的表单后,通过调用 doc.getForm().get(name) 并将其转换为具体的字段类型来检索命名字段的当前值:

try (Document doc = new Document("form.pdf")) {
    RadioButtonField radio = (RadioButtonField) doc.getForm().get("color");
    String selected = radio.getValue();
    System.out.println("Selected: " + selected);
}

另请参阅

 中文