Customizing form fields

Change the color and opacity of PDF Form Fields using this JavaScript sample (no servers or other external dependencies required). This is commonly used to highlight required fields in a form (signature fields) or to make important fields easier to find on a page. This sample works on all browsers (including IE11) and mobile devices without using plug-ins. To see an example launch our Form Field Customization demo. Learn more about our Web SDK.

1// eslint-disable-next-line no-undef
2const WebViewerConstructor = isWebComponent() ? WebViewer.WebComponent : WebViewer;
3
4WebViewerConstructor(
5 {
6 path: '../../../lib',
7 initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/form1.pdf',
8 },
9 document.getElementById('viewer')
10).then(instance => {
11 samplesSetup(instance);
12 const { documentViewer, annotationManager, Annotations } = instance.Core;
13
14 documentViewer.addEventListener('documentLoaded', () => {
15 const pageCount = documentViewer.getPageCount();
16 const defaultStyles = Annotations.WidgetAnnotation.getCustomStyles;
17 const defaultContainerStyles = Annotations.WidgetAnnotation.getContainerCustomStyles;
18 const customStyles = widget => {
19 if (widget instanceof Annotations.TextWidgetAnnotation) {
20 if (widget.fieldName === 'f1-1') {
21 return {
22 'background-color': 'lightgreen',
23 };
24 }
25 return {
26 'background-color': 'lightblue',
27 color: 'brown',
28 };
29 }
30 if (widget instanceof Annotations.PushButtonWidgetAnnotation) {
31 return {
32 'background-color': 'red',
33 color: 'white',
34 };
35 }
36 };
37
38 const customContainerStyles = widget => {
39 if (widget instanceof Annotations.WidgetAnnotation) {
40 return {
41 border: '2px solid green',
42 };
43 }
44 };
45
46 document.getElementById('form').onchange = e => {
47 if (e.target.id === 'custom') {
48 // Change styles for widget annotations
49 Annotations.WidgetAnnotation.getCustomStyles = customStyles;
50 Annotations.WidgetAnnotation.getContainerCustomStyles = customContainerStyles;
51 } else {
52 Annotations.WidgetAnnotation.getCustomStyles = defaultStyles;
53 Annotations.WidgetAnnotation.getContainerCustomStyles = defaultContainerStyles;
54 }
55 for (let i = 0; i < pageCount; i++) {
56 // Redraw canvas
57 annotationManager.drawAnnotations(i + 1, null, true);
58 }
59 };
60 });
61});

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales