Edit PDF form fields using JavaScript

You can update PDF form fields in two ways:

Understanding PDF form fields and widget annotations

PDF forms are composed of two related components:

  • Form field object — Stores data and logic, such as readOnly and required.

  • Widget annotation — Displays the form field visually on the page and controls appearance, such as backgroundColor or fontColor.

In the PDF specification, widget annotations are used to render form fields visually. A form field can be linked to one or more widget annotations, depending on how many times the field appears in the document. Understanding this relationship is important when customizing the appearance or behavior of form fields.

Programmatically editing form fields

The following example retrieves and updates a form field, along with its associated widget annotation:

const formFields = await instance.getFormFields();
const formField = formFields.find(
  (formField) => formField.name === "my form field"
);
const annotations = await instance.getAnnotations(0);
const widget = annotations.find(
  (annotation) => annotation.formFieldName === "my form field"
);
await instance.update([
  formField.set("required", true),
  widget.set("opacity", 0.5)
]);

The example above demonstrates the following steps:

  1. Retrieve all form fields in the document.

  2. Locate the form field by its name.

  3. Retrieve all annotations from page 0.

  4. Find the widget annotation linked to the form field.

  5. Update the form field and widget annotation in a single operation.

Key properties by component type

The form field and widget annotation objects expose different sets of properties. When editing form fields, it’s important to know which properties belong to which component.

Form field properties

  • required — Marks the field as mandatory.

  • readOnly — Prevents users from editing the field.

  • noExport — Excludes field data from export operations.

For a complete list of form field types and their properties, refer to the form fields API documentation.

Widget annotation properties

  • Visual properties — backgroundColor, borderColor, fontColor

  • Layout properties — borderWidth, fontSize, opacity

  • Alignment — horizontalAlign, verticalAlign

For a complete list of widget annotation properties, refer to the widget annotation API documentation.