In Chapter 9 of this manual, we already described the process of filling in a
form-like document (see Section 9.2).
The approach described in that chapter
had one serious drawback: individual blanks in a "form" had to be referenced
by their physical coordinates.
This is because the Section 9.2 code sample did not involve a real
form, but a regular (static) PDF document depicting a form.
Using tools such as Adobe Acrobat, it is possible
to place interactive fields on an existing document using
a graphical user interface. The form creator chooses a name, size,
location and other options for each field.
Once a form has been created, it can be filled in either interactively by a
user, or automatically using tools such as AspPDF.
A form field can be referenced by name, as opposed to (x, y)-coordinates,
which simplifies the coding significantly.
The PdfForm object provides the method FindField which returns
a PdfAnnot object representing a top-level form field with the specified name.
If no field under this name is found, the method returns Nothing.
Set Field = Doc.Form.FindField("txtLastName")
To specify a text value for a field, the method SetFieldValue
of the PdfAnnot object should be used. This method accepts two arguments: a text
string, and a font to be used to render the string.
The SetFieldValue method uses the field's pre-defined alignment and font
size parameters. It also preserves an existing field border if there is one.
The SetFieldValue method can be used to set a value not only for text fields, but
checkboxes, drop-down list boxes and radio buttons as well.
To select or unselect a checkbox, you must specify
a state name for the text string argument. The state name for the "on" state
should be obtained via the FieldOnValue property. The state name for the "off" state
is usually "Off".
When working with radio button groups, you need to use the PdfAnnot.Children
collection to reference each individual radio button within a group.
The code snippet below deselects radio button #1 (American Express) and selects
radio button #2 via the SetFieldValue method.
The following
code fragment fills out a credit card form generated
in Section 11.2:
' Credit card number
Set Field = Doc.Form.FindField("ccNumber")
Field.SetFieldValue "324234324234", Doc.fonts("Helvetica")
' Expiration month
Set Field = Doc.Form.FindField("ccMonth")
Field.SetFieldValue "Mar", Doc.fonts("Helvetica")
' Expiration year
Set Field = Doc.Form.FindField("ccYear")
Field.SetFieldValue "2010", Doc.fonts("Helvetica")
' "Need Receipt?" checkbox
Set Field = Doc.Form.FindField("Receipt")
Field.SetFieldValue Field.FieldOnValue, Nothing ' "on" state
' Credit card type (radio buttons)
Set Field = Doc.Form.FindField("ccType")
field.Children(1).SetFieldValue "Off", Nothing ' Unselect Amex
field.Children(2).SetFieldValue field.Children(2).FieldOnValue, Nothing ' Select Visa