Skip to main content

How to Fill PDF Form Fields in Java: Text Box, Checkbox, Combo Box & List Box

 

PDF forms are widely used for registration forms, applications, surveys, contract confirmations, and business approval processes. Unlike ordinary PDF documents, interactive PDF forms contain fields such as text boxes, checkboxes, radio buttons, combo boxes, and list boxes that can be filled programmatically.

When generating large numbers of application forms, importing customer data, or exporting completed forms from a business system, filling each form manually is inefficient. With Java, form fields can be read and populated automatically as part of a backend service, desktop application, or batch-processing workflow.

This article explains how to:

  • Read form fields from a PDF
  • Fill text boxes
  • Select radio button options
  • Check or clear checkboxes
  • Select items in list boxes and combo boxes
  • Populate fields based on their names
  • Save the completed PDF document


This method applies to PDF files that contain interactive form fields. It does not work directly with scanned PDFs, image-based forms, ordinary page content, or forms that have already been flattened.

1. Install the Required Java Library

The Java standard library does not provide built-in APIs for reading and filling PDF forms, so a third-party PDF library is required.

The examples in this article use Spire.PDF for Java to access and populate interactive form fields.

Option 1: Add the JAR File Manually

Download the library from:

After extracting the downloaded package, add Spire.Pdf.jar to the project build path.

In IntelliJ IDEA, open:

File > Project Structure > Modules > Dependencies

Then add the JAR file.

In Eclipse, right-click the project and select:

Build Path > Configure Build Path > Libraries

Then add the JAR file.

Option 2: Add the Maven Dependency

For Maven projects, add the following repository and dependency settings to pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.6.4</version>
    </dependency>
</dependencies>

2. Common PDF Form Field Types

A PDF form may contain several types of interactive controls. The program must first determine the field type before assigning a value.

Form fieldCorresponding classCommon method
Text boxPdfTextBoxFieldWidgetsetText()
Radio button groupPdfRadioButtonListFieldWidgetsetSelectedIndex()
List boxPdfListBoxWidgetFieldWidgetsetSelectedIndex()
CheckboxPdfCheckBoxWidgetFieldWidgetsetChecked()
Combo boxPdfComboBoxWidgetFieldWidgetsetSelectedIndex()

Radio buttons, list boxes, and combo boxes are usually selected by index.

Indexes start at 0:

  • Index 0 selects the first option
  • Index 1 selects the second option
  • Index 2 selects the third option

3. Fill All Form Fields in a PDF

The following example reads every form field in a PDF and assigns a value according to the field type.

Implementation Steps

  1. Create a PdfDocument object.
  2. Load the PDF form with loadFromFile().
  3. Retrieve the form through getForm().
  4. Get the form field collection.
  5. Iterate through the fields and determine each field type.
  6. Assign an appropriate value to each field.
  7. Save the completed PDF.
  8. Close the document and release resources.

Complete Code Example

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfCheckBoxWidgetFieldWidget;
import com.spire.pdf.widget.PdfComboBoxWidgetFieldWidget;
import com.spire.pdf.widget.PdfFormFieldWidgetCollection;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfListBoxWidgetFieldWidget;
import com.spire.pdf.widget.PdfRadioButtonListFieldWidget;
import com.spire.pdf.widget.PdfTextBoxFieldWidget;

public class FillFormFields {

    public static void main(String[] args) {

        String inputPath = "Forms.pdf";
        String outputPath = "FillFormFields.pdf";

        // Create a PdfDocument object
        PdfDocument document = new PdfDocument();

        try {
            // Load the PDF containing form fields
            document.loadFromFile(inputPath);

            // Retrieve the PDF form
            PdfFormWidget form =
                (PdfFormWidget) document.getForm();

            // Retrieve the form field collection
            PdfFormFieldWidgetCollection fields =
                form.getFieldsWidget();

            // Iterate through and fill all form fields
            for (int i = 0; i < fields.getCount(); i++) {

                PdfField field = fields.get(i);

                // Fill a text box
                if (field instanceof PdfTextBoxFieldWidget) {
                    PdfTextBoxFieldWidget textBox =
                        (PdfTextBoxFieldWidget) field;

                    textBox.setText("Kaila Smith");
                }

                // Select the second radio button option
                else if (
                    field instanceof PdfRadioButtonListFieldWidget
                ) {
                    PdfRadioButtonListFieldWidget radioButton =
                        (PdfRadioButtonListFieldWidget) field;

                    radioButton.setSelectedIndex(1);
                }

                // Select the first item in a list box
                else if (
                    field instanceof PdfListBoxWidgetFieldWidget
                ) {
                    PdfListBoxWidgetFieldWidget listBox =
                        (PdfListBoxWidgetFieldWidget) field;

                    listBox.setSelectedIndex(0);
                }

                // Check specific checkboxes by field name
                else if (
                    field instanceof PdfCheckBoxWidgetFieldWidget
                ) {
                    PdfCheckBoxWidgetFieldWidget checkBox =
                        (PdfCheckBoxWidgetFieldWidget) field;

                    switch (checkBox.getName()) {
                        case "checkbox1":
                        case "checkbox2":
                            checkBox.setChecked(true);
                            break;

                        default:
                            break;
                    }
                }

                // Select the second item in a combo box
                else if (
                    field instanceof PdfComboBoxWidgetFieldWidget
                ) {
                    PdfComboBoxWidgetFieldWidget comboBox =
                        (PdfComboBoxWidgetFieldWidget) field;

                    comboBox.setSelectedIndex(1);
                }
            }

            // Save the completed PDF
            document.saveToFile(
                outputPath,
                FileFormat.PDF
            );

            System.out.println(
                "The PDF form was filled successfully: "
                + outputPath
            );
        } finally {
            // Close the document and release resources
            document.close();
        }
    }
}

4. Code Explanation

Load the PDF Form

PdfDocument document = new PdfDocument();
document.loadFromFile("Forms.pdf");

PdfDocument represents and processes the PDF file. The loadFromFile() method loads the source document from the specified path.

Retrieve the PDF Form Object

PdfFormWidget form =
    (PdfFormWidget) document.getForm();

The getForm() method retrieves the form object contained in the PDF.

The returned object is cast to PdfFormWidget so that the interactive field collection can be accessed.

Retrieve All Form Fields

PdfFormFieldWidgetCollection fields =
    form.getFieldsWidget();

The getFieldsWidget() method returns all interactive form fields in the PDF.

Use the following method to retrieve the number of fields:

int fieldCount = fields.getCount();

A field can then be accessed by index:

PdfField field = fields.get(i);

Determine the Field Type

Each field is represented as a PdfField, but its actual type may differ. Use instanceof to identify the concrete field type.

For example:

if (field instanceof PdfTextBoxFieldWidget) {
    PdfTextBoxFieldWidget textBox =
        (PdfTextBoxFieldWidget) field;

    textBox.setText("Kaila Smith");
}

After identifying the type, cast the field to the corresponding widget class and call the appropriate setter method.

Save the Completed PDF

document.saveToFile(
    "FillFormFields.pdf",
    FileFormat.PDF
);

Save the result to a new file so that the original PDF form remains unchanged.

5. Fill Different Values Based on Field Names

The previous example fills every text box with the same value:

textBox.setText("Kaila Smith");

In a real application, different text boxes typically represent different values, such as a name, email address, phone number, or postal address.

In that case, assign values based on the field name.

Example

if (field instanceof PdfTextBoxFieldWidget) {

    PdfTextBoxFieldWidget textBox =
        (PdfTextBoxFieldWidget) field;

    String fieldName = textBox.getName();

    switch (fieldName) {
        case "name":
            textBox.setText("Kaila Smith");
            break;

        case "email":
            textBox.setText("kaila@example.com");
            break;

        case "phone":
            textBox.setText("13800000000");
            break;

        case "address":
            textBox.setText(
                "No. 100, Example Road"
            );
            break;

        default:
            break;
    }
}

This is more reliable than filling fields by index.

If the form design changes, the order of the fields may also change. As long as the field names remain the same, name-based matching can still locate the correct fields.

6. List All PDF Form Field Names and Types

Before writing the field-filling logic, it is often useful to inspect the form and determine which fields it contains.

The following code prints the name and type of every field:

PdfFormWidget form =
    (PdfFormWidget) document.getForm();

PdfFormFieldWidgetCollection fields =
    form.getFieldsWidget();

for (int i = 0; i < fields.getCount(); i++) {

    PdfField field = fields.get(i);

    System.out.println(
        "Field index: " + i
    );

    System.out.println(
        "Field name: " + field.getName()
    );

    System.out.println(
        "Field type: "
        + field.getClass().getSimpleName()
    );

    System.out.println("--------------------");
}

Example output:

Field index: 0
Field name: name
Field type: PdfTextBoxFieldWidget
--------------------
Field index: 1
Field name: gender
Field type: PdfRadioButtonListFieldWidget
--------------------
Field index: 2
Field name: checkbox1
Field type: PdfCheckBoxWidgetFieldWidget
--------------------

This information can then be used to create accurate field-mapping rules.

7. Fill Individual PDF Form Field Types

Fill a Text Box

PdfTextBoxFieldWidget textBox =
    (PdfTextBoxFieldWidget) field;

textBox.setText("Kaila Smith");

Text boxes are commonly used for:

  • Names
  • Addresses
  • Phone numbers
  • Email addresses
  • Notes
  • Application details

Select a Radio Button

PdfRadioButtonListFieldWidget radioButton =
    (PdfRadioButtonListFieldWidget) field;

radioButton.setSelectedIndex(1);

A radio button group allows only one option to be selected.

An index of 1 selects the second option.

Check or Clear a Checkbox

PdfCheckBoxWidgetFieldWidget checkBox =
    (PdfCheckBoxWidgetFieldWidget) field;

checkBox.setChecked(true);

To clear the checkbox, pass false:

checkBox.setChecked(false);

Select an Item in a List Box

PdfListBoxWidgetFieldWidget listBox =
    (PdfListBoxWidgetFieldWidget) field;

listBox.setSelectedIndex(0);

Index 0 selects the first item in the list.

Select an Item in a Combo Box

PdfComboBoxWidgetFieldWidget comboBox =
    (PdfComboBoxWidgetFieldWidget) field;

comboBox.setSelectedIndex(1);

Index 1 selects the second item in the combo box.

8. Practical Considerations

Confirm That the PDF Contains Interactive Form Fields

Not every PDF that looks like a form actually contains interactive fields.

The following files usually cannot be filled directly through form field APIs:

  • Scanned PDFs
  • Image-based application forms
  • Tables made from ordinary text and lines
  • Flattened PDF forms

You can check the number of detected fields first:

PdfFormWidget form =
    (PdfFormWidget) document.getForm();

PdfFormFieldWidgetCollection fields =
    form.getFieldsWidget();

if (fields.getCount() == 0) {
    System.out.println(
        "No interactive form fields were found in the PDF."
    );
}

Do Not Assume That Field Indexes Are Fixed

The following code depends on field order:

PdfField field = fields.get(0);

If the form is modified, its field order may change.

For production applications, prefer matching fields by name:

if ("email".equals(field.getName())) {
    // Fill the email field
}

Validate Option Indexes

Radio buttons, list boxes, and combo boxes are selected by index. An invalid index may cause an exception or fail to select the intended option.

Before setting an index, confirm:

  • How many options the field contains
  • Which index corresponds to the required option
  • Whether indexing starts at 0

Save the Result as a New File

Avoid overwriting the original template:

document.saveToFile(
    "Forms_Filled.pdf",
    FileFormat.PDF
);

Keeping the original blank form makes it easier to reuse the template.

Release Resources Properly

Always close the PdfDocument, regardless of whether the operation succeeds:

PdfDocument document =
    new PdfDocument();

try {
    document.loadFromFile("Forms.pdf");

    // Fill and save the form
} finally {
    document.close();
}

This is especially important when processing many files in a batch.

9. Frequently Asked Questions

Why Does the Program Find No Form Fields?

Possible reasons include:

  • The PDF is a scanned image
  • The visible input areas are only drawn rectangles
  • The form has already been flattened
  • The file uses a special form structure
  • The PDF does not contain interactive fields

Print fields.getCount() to check how many fields were detected.

Why Are All Text Boxes Filled with the Same Value?

The example applies the same instruction to every PdfTextBoxFieldWidget:

textBox.setText("Kaila Smith");

In a real application, assign values according to each field name.

How Can I Fill Only One Field?

Check the field name before assigning a value:

if (
    field instanceof PdfTextBoxFieldWidget
    && "name".equals(field.getName())
) {
    PdfTextBoxFieldWidget textBox =
        (PdfTextBoxFieldWidget) field;

    textBox.setText("Kaila Smith");
}

Why Is the Wrong Combo Box Item Selected?

setSelectedIndex() uses zero-based indexing.

For example:

comboBox.setSelectedIndex(0);

selects the first item, not the second.

How Can I Clear a Checkbox?

Pass false to setChecked():

checkBox.setChecked(false);

Can Multiple PDF Forms Be Filled in a Batch?

Yes. Iterate through the PDF files in a folder, create a separate PdfDocument for each file, fill the fields, and save each result separately.

When processing files in a batch:

  • Close each document after processing
  • Generate a unique output file name
  • Log files that fail
  • Avoid overwriting the original templates

Conclusion

Java can be used to automatically read and populate interactive PDF form fields.

For production use, first inspect the available field names and types, then populate each field by name. This is more reliable than depending on field indexes, especially when the PDF form template may change.

Also confirm that the source PDF contains interactive form fields. Scanned documents, ordinary page content, and flattened forms require a different approach.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...