Filling PDF form fields
Filling PDF form fields programmatically enables teams to automate document workflows, build form prepopulation systems, and implement data integration pipelines. Whether you’re creating automated form filling workflows for employee onboarding, building government form submission systems where applicant data prepopulates from databases, implementing insurance claim processing where policy information automatically fills claim forms, creating document assembly systems that merge data into form templates, or building batch processing workflows that fill thousands of forms from CSV or database records, programmatic form filling provides precise control over field values and states. Form filling operations include populating text fields with string values, setting checkbox checked states, selecting radio button options from groups, choosing dropdown (combo box) items from available options, and selecting single or multiple list box entries.
How Nutrient helps you achieve this
Nutrient Java SDK handles PDF form field manipulation, type casting, and value validation. With the SDK, you don’t need to worry about:
- Parsing PDF form field dictionaries and identifying field types correctly
- Managing field type casting and value format validation
- Handling field hierarchy traversal for nested field structures
- Complex field state management for checkboxes, radio buttons, and selections
Instead, Nutrient provides an API that handles all the complexity behind the scenes, letting you focus on your business logic.
Complete implementation
Below is a complete working example that demonstrates filling PDF form fields with various field types, including text fields, checkboxes, radio buttons, combo boxes (dropdowns), and list boxes. The following lines set up the Java application. Start by specifying a package name and importing the required classes:
package io.nutrient.Sample;
import io.nutrient.sdk.*;import io.nutrient.sdk.editors.*;import io.nutrient.sdk.editors.pdf.formfields.*;import io.nutrient.sdk.enums.*;
public class FillPdfForm {Create the main function:
public static void main(String[] args) {Opening a document with form fields
Open a PDF document that contains form fields using a try-with-resources statement for automatic resource cleanup. The following code opens the PDF document, creates a PDF editor instance with PdfEditor.edit(), and retrieves the form field collection using getFormFieldCollection(). This collection provides access to all form fields defined in the document, enabling iteration, lookup by name, and field value manipulation. The form field collection supports all PDF form field types, including text fields, checkboxes, radio buttons, combo boxes (dropdowns), list boxes, and signature fields:
try (Document document = Document.open("input_forms.pdf")) { PdfEditor editor = PdfEditor.edit(document); PdfFormFieldCollection formFields = editor.getFormFieldCollection();Filling a text field
Find a text field by name and set its value using type-specific methods. The following code uses findByFullName() to locate the text field by its fully qualified name "Text1" (including parent hierarchy if nested). The null check verifies the field exists in the document. The getFieldType() method returns the field type enumeration, and the comparison == PdfFormFieldType.Text confirms the field is a text input field before casting. The type cast (PdfTextField) textField converts the generic PdfFormField to the specific PdfTextField type, enabling access to text-specific methods like setValue(). The setValue("John Doe") call populates the text field with the string value "John Doe", which will display in the PDF form when opened in a viewer:
PdfFormField textField = formFields.findByFullName("Text1"); if (textField != null && textField.getFieldType() == PdfFormFieldType.Text) { ((PdfTextField) textField).setValue("John Doe"); }Checking a checkbox
Find a checkbox field and set its checked state using Boolean values. The following code locates the checkbox field "Check1" using findByFullName() and verifies it’s a checkbox type with getFieldType() == PdfFormFieldType.CheckBox before casting. The type cast (PdfCheckBoxField) checkbox enables access to checkbox-specific methods. The setIsChecked(true) method sets the checkbox to checked state (true = checked, false = unchecked). This operation updates the field’s appearance stream, causing PDF viewers to display the checkbox with a checkmark. Checkboxes are commonly used for binary yes/no selections, agreement acknowledgments, or opt-in/opt-out choices in forms:
PdfFormField checkbox = formFields.findByFullName("Check1"); if (checkbox != null && checkbox.getFieldType() == PdfFormFieldType.CheckBox) { ((PdfCheckBoxField) checkbox).setIsChecked(true); }Selecting a radio button option
Find a radio button group and select a specific option by its export value. The following code locates the radio button group "RadioGroup1" using findByFullName() and verifies it’s a radio button type with getFieldType() == PdfFormFieldType.RadioButton. Radio button groups contain multiple mutually exclusive options (buttons) that share the same parent field name. The type cast (PdfRadioButtonField) radioGroup enables access to radio button methods. The setSelectedOption("Option2") method selects the radio button with export value "Option2", automatically deselecting any previously selected option in the group. Each radio button in the group has a unique export value defining its identity, and only one option can be selected at a time. Radio buttons are commonly used for single-selection choices like gender, payment method, or preference selections:
PdfFormField radioGroup = formFields.findByFullName("RadioGroup1"); if (radioGroup != null && radioGroup.getFieldType() == PdfFormFieldType.RadioButton) { ((PdfRadioButtonField) radioGroup).setSelectedOption("Option2"); }Selecting an item in a combo box
Find a combo box (dropdown) field and select a specific item from its available options. The following code locates the combo box field "Dropdown1" using findByFullName() and verifies it’s a combo box type with getFieldType() == PdfFormFieldType.ComboBox. Combo boxes (also called dropdowns) display a list of predefined options when clicked, with only one option visible initially. The type cast (PdfComboBoxField) comboBox enables access to combo box-specific methods. The setSelectedValue("Germany") method selects the option with value "Germany" from the dropdown’s option list. The selected value must match exactly one of the predefined options configured in the form field’s option array. If the value doesn’t exist in the options, the selection fails silently. Combo boxes are commonly used for country selection, state/province selection, or category choices where users pick from a predefined list:
PdfFormField comboBox = formFields.findByFullName("Dropdown1"); if (comboBox != null && comboBox.getFieldType() == PdfFormFieldType.ComboBox) { ((PdfComboBoxField) comboBox).setSelectedValue("Germany"); }Selecting items in a list box
Find a list box field and select one or more items from its available options. The following code locates the list box field "List1" using findByFullName() and verifies it’s a list box type with getFieldType() == PdfFormFieldType.ListBox. List boxes display multiple options simultaneously in a scrollable list, unlike combo boxes, which show only one option initially. The type cast (PdfListBoxField) listBox enables access to list box-specific methods. The setSelectedValue("Technology") method selects the option with value "Technology" from the list. List boxes can be configured to allow single or multiple selections — when multiple selection is enabled, users can select several items by holding Controll/Command while clicking. The selected value(s) must match exactly one or more of the predefined options in the list box’s option array. List boxes are commonly used for multi-category selection, skills selection, or interest selection where users can see multiple options at once:
PdfFormField listBox = formFields.findByFullName("List1"); if (listBox != null && listBox.getFieldType() == PdfFormFieldType.ListBox) { PdfListBoxField list = (PdfListBoxField) listBox;
// Select an item by value list.setSelectedValue("Technology"); }Iterating and filling all fields
Fill multiple fields programmatically by iterating through the entire form field collection and applying batch operations. The following code demonstrates batch form filling using iteration and conditional logic. The outer loop iterates through all form fields in the collection. The getIsTerminal() check identifies terminal fields (leaf nodes with actual values) rather than parent container fields, and !getIsReadOnly() filters out read-only fields that shouldn’t be modified. The getFieldType() method returns the field type enumeration, enabling type-specific handling. The first conditional branch checks fieldType == PdfFormFieldType.Text to identify text fields, casts to PdfTextField, and sets a default value, "Sample Value". The second branch checks fieldType == PdfFormFieldType.CheckBox to identify checkboxes, casts to PdfCheckBoxField, and checks all checkboxes with setIsChecked(true). This batch processing pattern is commonly used for form prepopulation from database records, applying default values across multiple forms, or testing form layouts with sample data:
for (PdfFormField field : formFields) { if (field.getIsTerminal() && !field.getIsReadOnly()) { PdfFormFieldType fieldType = field.getFieldType();
if (fieldType == PdfFormFieldType.Text) { ((PdfTextField) field).setValue("Sample Value"); } else if (fieldType == PdfFormFieldType.CheckBox) { ((PdfCheckBoxField) field).setIsChecked(true); } } }Saving the filled form
Save the document with all filled form values to persist the field data. The following code uses saveAs() to write the modified document to a new file, "filled_form.pdf", preserving the original input file. The editor.close() call releases resources associated with the editor. All field values set during the session are embedded in the PDF structure, becoming part of the document’s permanent data. When users open the saved PDF in a viewer, all filled fields display the programmatically set values. The try-catch block captures any exceptions during form filling or saving, printing error messages and stack traces for debugging. This pattern ensures proper error handling for production workflows where form filling may fail due to invalid field names, type mismatches, or file system errors:
editor.saveAs("output_filled_form.pdf"); editor.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } }}Conclusion
The PDF form filling workflow consists of several key operations:
- Open the document using try-with-resources for automatic resource cleanup.
- Create a PDF editor and retrieve the form field collection with
getFormFieldCollection(). - The form field collection provides access to all form fields regardless of type.
- Use
findByFullName()to locate specific fields by their fully qualified names (including hierarchy). - Verify field types with
getFieldType()before casting to specific field classes. - Cast the generic
PdfFormFieldto specific types:PdfTextField,PdfCheckBoxField,PdfRadioButtonField,PdfComboBoxField,PdfListBoxField. - Fill text fields with
setValue(), using string values for text input. - Set checkbox states with
setIsChecked()using Boolean values (true= checked,false= unchecked). - Select radio button options with
setSelectedOption()using export values from the option group. - Select combo box items with
setSelectedValue()matching predefined dropdown options exactly. - Select list box items with
setSelectedValue()for single or multiple selection configurations. - Iterate all fields with conditional logic using
getIsTerminal()andgetFieldType()for batch filling operations. - Save the document with
saveAs()to persist all filled field values. - Handle exceptions with try-catch blocks for robust error recovery in production workflows.
Nutrient handles PDF form field dictionary parsing, field type identification, type casting validation, value format checking, and field appearance stream updates so you don’t need to understand PDF form field specifications or manage field state synchronization manually. The form filling system provides precise control for automated document workflows, form prepopulation from databases, data integration pipelines merging external data into form templates, batch processing workflows filling thousands of forms from CSV or database records, and document assembly systems creating filled forms from templates.