The tutorial shows you how to access the form fields in a PDF document and how to fill each form field with value by using Spire.PDF for Java.
Entire Code:
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.fields.PdfField; import com.spire.pdf.widget.*; public class FillFormField{ public static void main(String[] args){ //create a PdfDocument object PdfDocument doc = new PdfDocument(); //load a sample PDF containing forms doc.loadFromFile("G:\\java-workspace\\Spire.Pdf\\Forms.pdf"); //get the form fields from the document PdfFormWidget form = (PdfFormWidget) doc.getForm(); //get the form widget collection PdfFormFieldWidgetCollection formWidgetCollection = form.getFieldsWidget(); //loop through the widget collection and fill each field with value for (int i = 0; i < formWidgetCollection.getCount(); i++) { PdfField field = formWidgetCollection.get(i); if (field instanceof PdfTextBoxFieldWidget) { PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget) field; textBoxField.setText("Kaila Smith"); } if (field instanceof PdfRadioButtonListFieldWidget) { PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget) field; radioButtonListField.setSelectedIndex(1); } if (field instanceof PdfListBoxWidgetFieldWidget) { PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget) field; listBox.setSelectedIndex(0); } if (field instanceof PdfCheckBoxWidgetFieldWidget) { PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget) field; switch(checkBoxField.getName()){ case "checkbox1": checkBoxField.setChecked(true); break; case "checkbox2": checkBoxField.setChecked(true); break; } } if (field instanceof PdfComboBoxWidgetFieldWidget) { PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget) field; comboBoxField.setSelectedIndex(1); } } //Save the file doc.saveToFile("FillFormFields.pdf", FileFormat.PDF); } }
Output: