PDFOne (for Java)
Create, edit, view, print & enhance PDF documents and forms in Java SE/EE
Compatibility
J2SE J2EE Windows Linux Mac (OS X)

How to Create And Edit PDF Forms In Java

Learn how to create and modify form fields in PDF documents using PDFOne (for Java).
By Santhanam L.

Last month, we saw how to create new annotations and modify existing ones. This month, we will see how to create and edit PDF forms (AcroForms) documents.

PDFOne provides extensive support for programming PDF form fields. You can:

  1. Create form fields
  2. Fill form fields
  3. Modify form field properties
  4. Delete form fields
  5. Flatten form fields (remove interactivity but retain original value and appearance)

Introduction

Like HTML forms, PDF forms provide an interactive means for capturing data online, although many users obtain PDF forms documents only to fill the form fields and make a printed copy.

A PDF forms document contains form fields such as text boxes, list boxes, check boxes, and buttons.

PDFOne Support for AcroForms

In PDFOne (for Java), each form field type is represented by a class. To create a text box, we need to use an object of PdfFormTextField class. For a list box, an object of PdfFormComboBox class is required. A submit or reset button can be represented by a PdfFormPushButton object. All of these classes are derived from the base class PdfFormField.

Creating a PDF Forms Document

To create a PDF forms document:

  1. Create objects of various form fields.
  2. Construct the form fields using the various properties and method of the form field classes.
  3. Add the form fields to a page using the method PdfPage.addFormField(PdfFormField f).
  4. Add the page to the document and write the document to file or memory stream.

In the code snippet below, we see how this is done.

/*
 * Create a blank new PDF document
 * with a PdfWriter instance
 */
PdfWriter w = PdfWriter.fileWriter("formfields_doc1.pdf");

/*
 * Create a PdfDocument instance
 * with the PdfWriter instance
 */
PdfDocument d = new PdfDocument(w);


d.setOverrideFieldAppearanceStreams(true);

/*
 * Create a font and set its color
 */
PdfFont font =
	PdfFont.create("Helvetica",
			       10,
			       PdfEncodings.WINANSI);
font.setColor(Color.BLACK);

/*
 * Create page 1
 */
PdfPage p;
p = new PdfPage(PdfPageSize.A4);
p.setMeasurementUnit(PdfMeasurement.MU_INCHES);

/*
 * Add a new text box to page 1
 */
PdfFormTextField txtName =
	new PdfFormTextField(new PdfRect(3, 1.6, 4, .4));
txtName.setBackgroundColor(Color.LIGHT_GRAY);
txtName.setBorderColor(Color.DARK_GRAY);
txtName.setFont(font);
txtName.setName("ftf_name");
txtName.setValue("John Doe");
// Specify text shown in tool tip
txtName.setAlternateName("Enter your name here");
// Submits the value of this field in non-unicode text
txtName.setNameAsUnicode(false);
// Add the text box to the page
p.addFormField(txtName);

/*
 * Add a new list box to page 1
 */
PdfFormComboBox cboCountry =
	new PdfFormComboBox(new PdfRect(3, 2.6, 3, .4));
cboCountry.setBackgroundColor(Color.LIGHT_GRAY);
cboCountry.setBorderColor(Color.DARK_GRAY);
cboCountry.setName("flb_country");
cboCountry.addItem("England");
cboCountry.addItem("India");
cboCountry.addItem("USA");
cboCountry.addItem("Russia");
cboCountry.addItem("Germany");
cboCountry.setEditable(true);
cboCountry.setFont(font);
cboCountry.setValue("India");
cboCountry.setAlternateName("Select your country");
cboCountry.setNameAsUnicode(false);
// Add the list box to the page
p.addFormField(cboCountry);

/*
 * Add a new push button to page 1
 */
PdfFormPushButton btnSubmit =
	new PdfFormPushButton(new PdfRect(3, 3.6, 1, .4));
btnSubmit.setBackgroundColor(Color.LIGHT_GRAY);
btnSubmit.setBorderColor(Color.DARK_GRAY);
btnSubmit.setFont(font);
btnSubmit.setName("fbtn_submit");
btnSubmit.setNormalCaption("Submit");
// Specify URL to which form
// contents should be submitted 
btnSubmit.addActionFormSubmit(
            PdfEvent.ON_MOUSE_UP,
            "http://www.gnostice.com/newsletters/demos" +
            "/200803/pdfone_java/forms_submit_test.asp");
// Add the button to the page
p.addFormField(btnSubmit);

/*
 * Write text to page 1
 */
p.writeText("Name:", 2, 1.7);
p.writeText("Country:", 2, 2.7);

/*
 * Add page to document
 */
d.add(p);

/*
 * Save document to file
*/
d.setOpenAfterSave(true);
d.write();
w.dispose();

It is important to assign a name (not the object name) for your form field using the PdfFormField.setName(String name) method. When the document is submitted, the resource (website, viewer, or other application) that process the information submitted by the form, identifies individual form fields by this assigned name.

Modifying a PDF Forms Document

To modify a PDF forms document:

  1. Read the document.
  2. Retrieve the page where the form fields that need to be modified are present.
  3. Obtain a list of all form fields using PdfPage.getAllFormFields().
  4. Parse the list and identify form fields that need to be modified.
  5. Modify the form fields.
  6. Write document changes to the output file or stream.

In the code snippet below, we load the PDF forms document that was created earlier and add some extra options in the list box.

/*
 * Read a forms document with a PdfReader instance
 * and specify output file for saving changes 
 */
PdfReader r = 
	PdfReader.fileReader("formfields_doc1.pdf");
r.setOutFilePath("formfields_doc2.pdf");

/*
 * Create a PdfDocument instance with 
 * the PdfReader instance 
*/
PdfDocument d = new PdfDocument(r);

d.setOverrideFieldAppearanceStreams(true);

/*
 * Get page 1 from the document
*/ 
PdfPage p = d.getPage(1);

/*
 * Get all form fields from page 1
*/
List fieldList = p.getAllFormFields();

/*
 * Parse through all form fields and find 
 * the list box by its name
*/
for (Iterator iter = fieldList.iterator(); iter.hasNext();)
{
    PdfFormField fld = (PdfFormField) iter.next();
    
    // Identify if current field is a list box
    // and has a matching name 
    if (fld instanceof PdfFormComboBox &&
	fld.getName().equals("flb_country"))
    {
        PdfFormComboBox cboFld = (PdfFormComboBox) fld;
        
        // Add more options to the identified list box
        cboFld.addItem("Japan");
        cboFld.addItem("China");
        cboFld.addItem("Papua New Guinea");
        cboFld.addItem("Other");                    
    }
}

/*
 * Save changes to file
*/
d.setOpenAfterSave(true);
d.write();
r.dispose();

---o0O0o---

Our .NET Developer Tools
Gnostice Document Studio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
Gnostice Document Studio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
XtremeDocumentStudio (for Java)

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2019 Gnostice Information Technologies Private Limited. All rights reserved.