Aspose.Words

Form Fields in Aspose.Words

Placing form fields into the document via code is easy. DocumentBuilder has special methods for inserting them, one for each form field type.

Each of the methods accepts a string parameter representing the name of the form field. The name can be an empty string. If however you specify a name for the form field, then a bookmark is automatically created with the same name.

Inserting Form Fields

Use DocumentBuilder.InsertTextInput, DocumentBuilder.InsertCheckBox or DocumentBuilder.InsertComboBox to insert form fields into a document.

Example DocumentBuilderInsertComboBoxFormField

Shows how to insert a combobox form field into a document.

[Java]

 

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

 

String[] items = {"One", "Two", "Three"};

builder.insertComboBox("DropDown", items, 0);

 

 

Obtaining Form Fields

A collection of form fields is represented by the FormFieldCollection class that can be retrieved using the Range.FormFields property. This means that you can obtain form fields contained in any document node including the document itself.

Example FormFieldsGetFormFieldsCollection

Shows how to get a collection of form fields.

[Java]

 

Document doc = new Document(getMyDir() + "FormFields.doc");

FormFieldCollection formFields = doc.getRange().getFormFields();

 

 

You can get a particular form field by its index or name.

Example FormFieldsGetByName

Shows how to access form fields.

[Java]

 

Document doc = new Document(getMyDir() + "FormFields.doc");

FormFieldCollection documentFormFields = doc.getRange().getFormFields();

 

FormField formField1 = documentFormFields.get(3);

FormField formField2 = documentFormFields.get("CustomerName");

 

 

The FormField properties allow you to work with form field name, type, and result.

Example FormFieldsWorkWithProperties

Shows how to work with form field name, type, and result.

[Java]

 

Document doc = new Document(getMyDir() + "FormFields.doc");

 

FormField formField = doc.getRange().getFormFields().get(3);

 

if (formField.getType() == FieldType.FIELD_FORM_TEXT_INPUT)

    formField.setResult("My name is " + formField.getName());