How to Work with Interactive Forms in Java

How to Work with Interactive Forms in Java

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, and text fields, and to read submitted form field values.

Create a Radio Button Group

RadioButtonField represents a group of mutually exclusive options. Each option is added with a label and a Rectangle bounding box. Set the initial value by calling setValue() with one of the option labels:

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

Add a Checkbox

A CheckboxField is a single boolean field. Set setChecked(true) to make it checked by default. The field is added 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(50, 50, 70, 70));
    cb.setPartialName("agree");
    cb.setChecked(true);
    doc.getForm().add(cb, 1);
    doc.save("form.pdf");
}

Add a Text Field

TextBoxField accepts user 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("Enter your name");
    doc.getForm().add(text, 1);
    doc.save("form.pdf");
}

Get the Selected Value

After loading a form, retrieve the current value of a field by its partial name. Cast the field to its concrete type to call type-specific methods:

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

See Also

 English