Some test text!

Search
Hamburger Icon

Web / Guides / Fill form fields

Fill PDF form fields in JavaScript

This guide will walk you through how to programmatically fill out PDF form fields. You can also try it now with our form fill demo.

Filling widget values

You can fill widget values by using the WidgetAnnotation.setValue API. This also internally updates the associated field value.The following sample code shows how to clear the value of all widgets in a document.

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

  documentViewer.addEventListener('annotationsLoaded', () => {
    const widgets = annotationManager.getAnnotationsList().filter(annotation => annotation instanceof Annotations.WidgetAnnotation);
    widgets.forEach((widget) => {
      widget.setValue('');
    });
  });
});

Listening for widget events

Interacting with widget annotations causes a number of events to be fired. The following sample demonstrates how to respond to the ‘focus’ event.

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

  const DEFAULT_VALUE = 'N/A';

  documentViewer.addEventListener('annotationsLoaded', () => {
    const textWidgets = annotationManager.getAnnotationsList().filter(annotation => annotation instanceof Annotations.TextWidgetAnnotation);
    textWidgets.forEach((widget) => {
      widget.addEventListener('focus', () => {
        if (!widget.getValue()) {
          widget.setValue(DEFAULT_VALUE);
          annotationManager.redrawAnnotation(widget);
        }
      });
    });
  });
});

Filling field values

You can access and fill any form field by its field name. The following sample demonstrates how to get a field by its name and set a new value.

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

  documentViewer.addEventListener('annotationsLoaded', () => {
    const fieldManager = annotationManager.getFieldManager();
    const fieldName = ''; // Add field name here.
    const field = fieldManager.getField(fieldName);
    if (field) {
      field.setValue('new value');
    }
  });
});

Listening for field changes

The fieldChanged event is fired any time the value of a form field changes. The following sample shows how to listen to the event and log the changed field's name and value.

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

  annotationManager.addEventListener('fieldChanged', (field, value) => {
    console.log(`Field changed: ${field.name}, ${value}`);
  });
});

Trial setup questions? Ask experts on Discord
Need other help? Contact Support
Pricing or product questions? Contact Sales