Some test text!

Search
Hamburger Icon

Web / Guides / Modify form fields

Modifying PDF form fields in Javascript

This guide will walk you through how to iterate over fields, get a specific field by its name and modify properties on PDF form fields.

The following code sets all fields to readonly when the document is loaded. The annotationChanged event is triggered when the annotations are added to the document and checking the action and e.imported ensures that they changed because of an import into the document and not because of a user modification.

WebViewer(...)
.then(instance => {
  const { annotationManager, Annotations } = instance.Core;

  annotationManager.addEventListener('annotationChanged', (annotations, action, { imported }) => {
    // if the annotation change occurs because of an import then
    // these are fields from inside the document
    if (imported && action === 'add') {
      annotations.forEach(function(annot) {
        if (annot instanceof Annotations.WidgetAnnotation) {
          annot.fieldFlags.set('ReadOnly', true);
        }
      });
    }
  });
});

Iterate over all fields

You can iterate over all fields using the forEachField function of FieldManager.

Note that you'll need to wait for the annotationsLoadedPromise to resolve to ensure that the fields are accessible in the FieldManager.
WebViewer(...)
.then(instance => {
  const { documentViewer, annotationManager } = instance.Core;

  const getFieldNameAndValue = (field) => {
    // Do something with data
    const { name, value } = field;
    console.log(`Name: ${name}, Value: ${value}`);

    // Check children fields
    field.children.forEach(getFieldNameAndValue);
  }

  documentViewer.addEventListener('annotationsLoaded', () => {
    const fieldManager = annotationManager.getFieldManager();
    fieldManager.forEachField(getFieldNameAndValue);
  });
});

Accessing fields by name

You can access any field by its field name:

WebViewer(...)
.then(instance => {
  const { documentViewer, annotationManager } = instance.Core;

  documentViewer.addEventListener('documentLoaded', () => {
    documentViewer.getAnnotationsLoadedPromise().then(function() {
      const fieldManager = annotationManager.getFieldManager();
      const field = fieldManager.getField('fieldName');
      field.widgets.map(annot => {
        annot.fieldFlags.set('ReadOnly', true);
      });
    });
  });
});

Get the answers you need: Chat with us