How to update form values programmatically
JPedal has a selection of tools that can be used together to achieve many different tasks. In this case we can use the PDFFormUtilities and FormWriter in order to update form values programmatically.
This is done by getting the FormObjects from PDFFormUtilities, modifying them, and then saving them with the FormWriter.
Getting the FormObjects
The FormObjects can be retrieved using the PDFFormUtilities and has been documented here.
In order to get the FormObjects you will need to do the following. The below example shows how to get all formObjects or just those on one page.
final PdfFormUtilities formUtils = new PdfFormUtilities("inputFile.pdf");
try {
if (formUtils.openPDFFile()){
final FormObject[] formArray = (FormObject[]) formUtils.getFormComponentsFromDocument(null,ReturnValues.FORMOBJECTS_FROM_REF);
final int page = 1;
final FormObject[] formArrayForPage = (FormObject[]) formUtils.getFormComponentsFromPage(null, ReturnValues.FORMOBJECTS_FROM_REF, page);
}
} catch (PdfException e) {
e.printStackTrace();
} finally {
formUtils.closePDFfile();
}
Modifying the FormObjects
Now that you have access to the FormObjects you can begin to modify them. The values of the FormObjects are accessed by methods based on the data type. There are multiple different values that you may wish to update, to find what values to update we recommend reading the PDF Reference Chapter on Interactive Forms.
Save the updated Forms
Once the form objects have been updated you can save the values with a simple line of code.
FormWriter.writeForm is a static method that takes the original file, the file your wish to save to (can be the original file or a new copy), and a list of FormObjects to save to the file.
final File originalFile = new File("inputFile.pdf");
final File updatedFile = new File("outputFile.pdf");
final FormObject[] formArray; //Created and modified earlier
FormWriter.writeForms(originalFile, updatedFile, formArray);