Some test text!

menu

Customize PDF form field styles with JavaScript

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 IE10) and mobile devices without using plug-ins. To see an example launch our Form Field Customization demo. Learn more about our JavaScript PDF Library.

Get StartedSamplesDownload

To run this sample, get started with a free trial of PDFTron SDK.

JavaScript

HTML

WebViewer(
  {
    path: '../../../lib',
    pdftronServer: 'https://demo.pdftron.com/', // comment this out to do client-side only
    initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/form1.pdf',
  },
  document.getElementById('viewer')
).then(instance => {
  samplesSetup(instance);
  const { docViewer, annotManager, Annotations } = instance;

  docViewer.on('documentLoaded', () => {
    const pageCount = docViewer.getPageCount();
    const defaultStyles = Annotations.WidgetAnnotation.getCustomStyles;
    const defaultContainerStyles = Annotations.WidgetAnnotation.getContainerCustomStyles;
    const customStyles = widget => {
      if (widget instanceof Annotations.TextWidgetAnnotation) {
        if (widget.fieldName === 'f1-1') {
          return {
            'background-color': 'lightgreen',
          };
        }
        return {
          'background-color': 'lightblue',
          color: 'brown',
        };
      }
      if (widget instanceof Annotations.PushButtonWidgetAnnotation) {
        return {
          'background-color': 'red',
          color: 'white',
        };
      }
    };

    const customContainerStyles = widget => {
      if (widget instanceof Annotations.WidgetAnnotation) {
        return {
          border: '2px solid green',
        };
      }
    };

    document.getElementById('form').onchange = e => {
      if (e.target.id === 'custom') {
        // Change styles for widget annotations
        Annotations.WidgetAnnotation.getCustomStyles = customStyles;
        Annotations.WidgetAnnotation.getContainerCustomStyles = customContainerStyles;
      } else {
        Annotations.WidgetAnnotation.getCustomStyles = defaultStyles;
        Annotations.WidgetAnnotation.getContainerCustomStyles = defaultContainerStyles;
      }
      for (let i = 0; i < pageCount; i++) {
        // Redraw canvas
        annotManager.drawAnnotations(i + 1, null, true);
      }
    };
  });
});
close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.