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.

1WebViewer(...)
2.then(instance => {
3 const { documentViewer, annotationManager, Annotations } = instance.Core;
4
5 documentViewer.addEventListener('annotationsLoaded', () => {
6 const widgets = annotationManager.getAnnotationsList().filter(annotation => annotation instanceof Annotations.WidgetAnnotation);
7 widgets.forEach((widget) => {
8 widget.setValue('');
9 });
10 });
11});

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.

1WebViewer(...)
2.then(instance => {
3 const { documentViewer, annotationManager, Annotations } = instance.Core;
4
5 const DEFAULT_VALUE = 'N/A';
6
7 documentViewer.addEventListener('annotationsLoaded', () => {
8 const textWidgets = annotationManager.getAnnotationsList().filter(annotation => annotation instanceof Annotations.TextWidgetAnnotation);
9 textWidgets.forEach((widget) => {
10 widget.addEventListener('focus', () => {
11 if (!widget.getValue()) {
12 widget.setValue(DEFAULT_VALUE);
13 annotationManager.redrawAnnotation(widget);
14 }
15 });
16 });
17 });
18});

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.

1WebViewer(...)
2.then(instance => {
3 const { documentViewer, annotationManager } = instance.Core;
4
5 documentViewer.addEventListener('annotationsLoaded', () => {
6 const fieldManager = annotationManager.getFieldManager();
7 const fieldName = ''; // Add field name here.
8 const field = fieldManager.getField(fieldName);
9 if (field) {
10 field.setValue('new value');
11 }
12 });
13});

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.

1WebViewer(...)
2.then(instance => {
3 const { annotationManager } = instance.Core;
4
5 annotationManager.addEventListener('fieldChanged', (field, value) => {
6 console.log(`Field changed: ${field.name}, ${value}`);
7 });
8});

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales