Edit PDF Form Fields in Java

This guide explains how to set values on form fields in PSPDFKit for Java. See the Extract Form Field Values guide for information on how to get values.

To fill form fields, a basic model of the data must be built and passed to a single API. To ensure the API is flexible, the form field values are applied using a JSON object. The following code shows a simple example of form filling:

final PdfDocument document = PdfDocument.open(new FileDataProvider(new File("formDocument.pdf")));
FormProvider formProvider = document.getFormProvider();

// Construct the key-value form fields.
final JSONObject valuesToSet = new JSONObject();
valuesToSet.put("first_name", "John");
valuesToSet.put("last_name", "Smith");

// Finally, apply them to the document.
formProvider.setFormFieldValuesJson(valuesToSet);

Here, you can see two form field names, Name_First and Name_Last. These fields are populated with the strings John and Smith, respectively. Passing the JSON object to FormProvider.setFormFieldValuesJson will set the form fields in the current document. If an error occurs or the field names cannot be found, an exception with a description of the error will be thrown.

Form Values JSON Format

Each object of the JSON object must hold a key — which is the unique name of the form field (often referred to as fully qualified name) — with the value of JSON type null, string, or Array. A null value will reset the form field to either null or its default value, if available.