Fill PDF Form Fields in Java
PSPDFKit Libraries supports the AcroForm standard, and the API is exposed to allow the filling of form fields.
Forms are an optional component that can be licensed. If not licensed, calling any Form API will result in an exception thrown. Please contact support to enquire about support for Forms.
It is incredibly easy to fill out form fields. All that is required is that you build up a model of the data and call a single API. To ensure the API is flexible, the form field values are returned in a JSON object. The following code shows a simple example of form filling:
PdfDocument document = PdfDocument.open(new FileDataProvider(new File("formDocument.pdf"))); FormProvider formProvider = document.getFormProvider(); // Construct the key value form fields and apply them to the document. JSONObject valuesToSet = new JSONObject(); valuesToSet.put("Name_First", "John"); valuesToSet.put("Name_Last", "Smith"); document.getFormProvider().setFormFieldValuesJson(valuesToSet);
Here we can see two form field names,
Name_Last. These fields are being populated with the strings
Smith, respectively. Passing the JSON object to
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.
To extract the form field values, the process is similar:
PdfDocument document = PdfDocument.open(new FileDataProvider(new File("formDocument.pdf"))); JSONObject formFieldValues = document.getFormProvider().getFormFieldValuesJson(); assertEquals("John", formFieldValues.get("Name_First")); assertEquals("Smith", formFieldValues.get("Name_Last"));
Above, we can see the extraction of the form field’s values. The extracted values are held in the exact same key-value pair structure the form field value setter requires. When we query the
Name_First key, we retrieve the string