Access and Find PDF Form Fields
- 2 minutes to read
Use the PdfDocument.getFields() method to access a PDF document’s form field collection. You can iterate through all fields, find a field by name, find fields that match a condition, or locate a field’s parent group.
Access All Form Fields
Call the PdfDocument.getFields() method to get the document’s form field collection and iterate through its fields.
The following code snippet iterates through all form fields and prints their names and types:
// Iterate through all form fields in the document, including grouped fields.
for (FormField field : pdfDocument.getFields().toFlatIterable()) {
System.out.println(field.getName());
System.out.println(field.getClass().getSimpleName());
}
Refer to the following help topics for additional information on processing fields that belong to groups:
Find a Form Field by Name
Call the findByName() method to get a form field with the specified name.
The following code snippet searches for the FirstName field:
// Find a form field by name.
FormField field = pdfDocument.getFields().findByName("FirstName");
if (field != null) {
System.out.println(field.getName());
}
Find the First Matching Form Field
Call the find(Predicate<FormField>) method to find the first form field that satisfies the specified condition.
The following code snippet finds the first field whose name starts with First:
// Find the first matching form field.
FormField field = pdfDocument.getFields().find(
f -> f.getName().startsWith("First"));
if (field != null) {
System.out.println(field.getName());
}
Find Multiple Form Fields
Call the findAll(Predicate<FormField>) method to get all fields that satisfy the specified condition.
The following code snippet finds all fields whose names contain Name:
// Find all matching form fields.
Iterable<FormField> fields =
pdfDocument.getFields().findAll(
f -> f.getName().contains("Name"));
for (FormField field : fields) {
System.out.println(field.getName());
}
Find a Field’s Parent Group
If a field belongs to a group, call the findParent(FormField) method to obtain its parent GroupField.
The following code snippet obtains the parent group of a form field:
// Find a form field.
FormField field = pdfDocument.getFields().findByName("FirstName");
// Get the parent group.
GroupField group = pdfDocument.getFields().findParent(field);
if (group != null) {
System.out.println(group.getName());
}