Form Fields

Form Fields (4)

Thursday, 26 September 2019 09:10

Read and Extract Fillable Form Values in PDF in Java

Written by support iceblue

Spire.PDF for Java empowers developers to read and extract value from a specific form field as well as read and extract values from all form fields. In this article, we'll see how to use Spire.PDF for Java to implement this function.

Below is the sample PDF document we used for demonstration:

Read and Extract Fillable Form Values in PDF in Java

Read and extract value from a specific form field

import com.spire.pdf.PdfDocument;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfTextBoxFieldWidget;

import java.io.FileWriter;
import java.io.IOException;


public class ReadSpeicificFormValue {
    public static void main(String[] args){
        //Load PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("fillFormFields.pdf");

        //Get form fields
        PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm();

        //Get the textbox by index or by name
        PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get(0);
        //PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get("TextBox");

        //Get the text of the textbox
        String text = textbox.getText();

        try {
            //Write text into a .txt file
            FileWriter writer = new FileWriter("GetSpecificFieldValue.txt");
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pdf.close();
    }
}

Read and Extract Fillable Form Values in PDF in Java

Read and extract values from all form fields

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.*;

import java.io.FileWriter;
import java.io.IOException;


public class ReadAllFormValues {
    public static void main(String[] args)
        //Load PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("fillFormFields.pdf");

        //Get form fields
        PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm();

        StringBuilder sb = new StringBuilder();
        //Loop through the form field widget collection and extract the value of each field
        for (int i = 0; i < formWidget.getFieldsWidget().getCount(); i++)
        {
            PdfField field = (PdfField)formWidget.getFieldsWidget().getList().get(i);
            if (field instanceof PdfTextBoxFieldWidget)
            {
                PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field ;
                //Get text of textbox
                String text = textBoxField.getText();
                sb.append("The text in textbox is: " + text + "\r\n");
            }

            if (field instanceof PdfListBoxWidgetFieldWidget)
            {
                PdfListBoxWidgetFieldWidget listBoxField = (PdfListBoxWidgetFieldWidget)field;
                sb.append("Listbox items are: \r\n");
                //Get values of listbox
                PdfListWidgetItemCollection items = listBoxField.getValues();

                for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items)
                {
                    sb.append(item.getValue() + "\r\n");
                }
                //Get selected value
                String selectedValue = listBoxField.getSelectedValue();
                sb.append("The selected value in the listbox is: " + selectedValue + "\r\n");
            }

            if (field instanceof PdfComboBoxWidgetFieldWidget)
            {
                PdfComboBoxWidgetFieldWidget comBoxField = (PdfComboBoxWidgetFieldWidget)field ;
                sb.append("comBoxField items are: \r\n");
                //Get values of comboBox
                PdfListWidgetItemCollection items = comBoxField.getValues();

                for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items)
                {
                    sb.append(item.getValue() + "\r\n");
                }
                //Get selected value
                String selectedValue = comBoxField.getSelectedValue();
                sb.append("The selected value in the comBoxField is: " + selectedValue + "\r\n");
            }

            if (field instanceof PdfRadioButtonListFieldWidget)
            {
                PdfRadioButtonListFieldWidget radioBtnField = (PdfRadioButtonListFieldWidget)field;
                //Get value of radio button
                String value = radioBtnField.getValue();

                sb.append("The text in radioButtonField is: " + value + "\r\n");
            }

            if (field instanceof PdfCheckBoxWidgetFieldWidget)
            {
                PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field;
                //Get the checked state of the checkbox
                boolean state = checkBoxField.getChecked();
                sb.append("Is the checkBox checked? " + state + "\r\n");
            }
        }

        try {
            //Write text into a .txt file
            FileWriter writer = new FileWriter("GetAllValues.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pdf.close();
    }
}

Read and Extract Fillable Form Values in PDF in Java

This article demonstrates how to detect the required form fields in an existing PDF document using Spire.PDF for Java.

import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class DetectRequiredFields {

    public static void main(String[] args) {

        //load a PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Fields.pdf");

        //get form widget from the PDF document.
        PdfFormWidget formWidget = (PdfFormWidget)doc.getForm();

        //loop through the fields widget
        for (int i = 0; i < formWidget.getFieldsWidget().getList().getCapacity(); i++) {

            //get the specific field
            PdfField field = (PdfField) formWidget.getFieldsWidget().getList().get_Item(i);

            //get the field name
            String fieldName = field.getName();

            //determine if the field is required
            boolean isRequired = field.getRequired();
            if (isRequired){

                //print the required field
                System.out.println(fieldName + " is required");
            }
        }
    }
}

Detect Required Fields in a PDF Document in Java

Monday, 22 October 2018 03:00

Fill PDF Form Fields in Java

Written by support iceblue

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:

Fill PDF Form Fields in Java

Monday, 08 October 2018 07:18

Create Fillable Form Fields in PDF in Java

Written by support iceblue

PDF fillable forms, also known as the interaction forms, are mainly used to collect user information. The most common form fields include text box, radio button, check box, list box and combo box. The code snippets below demonstrate how to add fillable form fields to PDF using Spire.PDF for Java.

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.EnumSet;

import com.spire.pdf.fields.*;
import com.spire.pdf.graphics.*;

public class AddFormFieldsToPdf {

	public static void main(String[] args) throws Exception {
		
        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        
		//add a page
		PdfPageBase page = doc.getPages().add();

		//initialize x and y coordinates
		float baseX = 100;
		float baseY = 0;

        //create brush objects
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.black));
         
        //create font 
        PdfFont font = new PdfFont(PdfFontFamily.Times_Roman, 12f, EnumSet.of(PdfFontStyle.Regular));

        //add a textbox to pdf
        String text = "TextBox:"; 
        page.getCanvas().drawString(text, font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float tbxBounds = new Rectangle2D.Float(baseX, baseY , 150, 15);
        PdfTextBoxField textBox = new PdfTextBoxField(page, "textbox");
        textBox.setBounds(tbxBounds);
        textBox.setText("Hello World");
        textBox.setFont(font);
        doc.getForm().getFields().add(textBox);
        baseY +=25;

        //add checkboxes to pdf
        page.getCanvas().drawString("CheckBox:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec1 = new java.awt.geom.Rectangle2D.Float(baseX, baseY, 15, 15);
        PdfCheckBoxField checkBoxField = new PdfCheckBoxField(page, "checkbox1");
        checkBoxField.setBounds(rec1);
        checkBoxField.setChecked(false);
        page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY));
        java.awt.geom.Rectangle2D.Float rec2 = new java.awt.geom.Rectangle2D.Float(baseX + 70, baseY, 15, 15);
        PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "checkbox2");
        checkBoxField1.setBounds(rec2);
        checkBoxField1.setChecked(false);
        page.getCanvas().drawString("Option 2", font,  brush2, new Point2D.Float(baseX+90, baseY));
        doc.getForm().getFields().add(checkBoxField);
        doc.getForm().getFields().add(checkBoxField1);
        baseY += 25;

        //add a listbox to pdf
        page.getCanvas().drawString("ListBox:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec = new java.awt.geom.Rectangle2D.Float(baseX, baseY, 150, 50);
        PdfListBoxField listBoxField = new PdfListBoxField(page, "listbox");
        listBoxField.getItems().add(new PdfListFieldItem("Item 1", "item1"));
        listBoxField.getItems().add(new PdfListFieldItem("Item 2", "item2"));
        listBoxField.getItems().add(new PdfListFieldItem("Item 3", "item3"));;
        listBoxField.setBounds(rec);
        listBoxField.setFont(font);
        listBoxField.setSelectedIndex(0);
        doc.getForm().getFields().add(listBoxField);
        baseY += 60;

        //add radiobuttons to pdf
        page.getCanvas().drawString("RadioButton:", font, brush1, new Point2D.Float(0, baseY));
        PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "radio");
        PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("option1");
        radioItem1.setBounds(new Rectangle2D.Float(baseX, baseY, 15, 15));
        page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY));
        PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("option2");
        radioItem2.setBounds(new Rectangle2D.Float(baseX + 70, baseY, 15, 15));
        page.getCanvas().drawString("Option 2", font, brush2, new Point2D.Float(baseX + 90, baseY));
        radioButtonListField.getItems().add(radioItem1);
        radioButtonListField.getItems().add(radioItem2);
        radioButtonListField.setSelectedIndex(0);
        doc.getForm().getFields().add(radioButtonListField);
        baseY += 25;

        //add a combobox to pdf
        page.getCanvas().drawString("ComboBox:", font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float cmbBounds = new Rectangle2D.Float(baseX, baseY, 150, 15);
        PdfComboBoxField comboBoxField = new PdfComboBoxField(page, "combobox");
        comboBoxField.setBounds(cmbBounds);
        comboBoxField.getItems().add(new PdfListFieldItem("Item 1", "item1"));
        comboBoxField.getItems().add(new PdfListFieldItem("Item 2", "itme2"));
        comboBoxField.getItems().add(new PdfListFieldItem("Item 3", "item3"));
        comboBoxField.getItems().add(new PdfListFieldItem("Item 4", "item4"));
        comboBoxField.setSelectedIndex(0);      
        comboBoxField.setFont(font);
        doc.getForm().getFields().add(comboBoxField);
        baseY += 25;

        //add a signature field to pdf
        page.getCanvas().drawString("Signature:", font, brush1, new Point2D.Float(0, baseY));
        PdfSignatureField sgnField= new PdfSignatureField(page,"sgnField");
        Rectangle2D.Float sgnBounds = new Rectangle2D.Float(baseX, baseY, 150, 80);
        sgnField.setBounds(sgnBounds);
        doc.getForm().getFields().add(sgnField);
        baseY += 90;

        //add a button to pdf
        page.getCanvas().drawString("Button:", font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float btnBounds = new Rectangle2D.Float(baseX, baseY, 50, 15);
        PdfButtonField buttonField = new PdfButtonField(page, "button");
        buttonField.setBounds(btnBounds);
        buttonField.setText("Sumbit");
        buttonField.setFont(font);
        doc.getForm().getFields().add(buttonField);

        //save to file
        doc.saveToFile("AddFormField-2.pdf", FileFormat.PDF);
	}

}

Create Fillable Form Fields in PDF in Java