Interactive Forms

This guide shows how to create and manage AcroForm fields in PDF documents using Aspose.PDF FOSS for Java. You will learn to add radio buttons, checkboxes, text fields, combo boxes, and list boxes, and to retrieve submitted field values.

AcroForm API

The Form class, accessible via Document.getForm(), manages all AcroForm fields in the document. Fields are added by calling Form.add(field, pageNumber).

RadioButtonField

Create a group of radio buttons, each option at its own Rectangle. Each option is added with a label and a bounding box. Call setValue() to pre-select an option:

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() selects an option programmatically. getValue() returns the currently selected option name.

CheckboxField

CheckboxField represents a single boolean input field in the PDF form. Set setChecked(true) to make the field checked by default. Add it to the form at a specific page number (1-indexed):

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 accepts freeform text input. Set a default value with setValue() and register the field with the form before saving:

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 and ListBoxField

ComboBoxField and ListBoxField present selectable option lists. Both accept option strings via addOption() and expose getValue() to retrieve the selection.

FormEditor

FormEditor is a facade class for working with AcroForm fields. Bind a document with bindPdf(), apply changes, then call save().

Reading Field Values

After loading a filled form, retrieve the current value of a named field by calling doc.getForm().get(name) and casting to the concrete field type:

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

See Also

 English