Some test text!

menu
Watermarkkeyboard_arrow_down

Add Watermark to PDF using JavaScript

Adding text or an image as a watermark on top of a document requires only a few lines of code using the setWatermark method of DocumentViewer. This method allows you to pass an options object to draw text on top of the document or pass a custom function which will be executed with a reference to the page canvas.

linkDraw text as watermark

To draw a watermark, use docViewer.setWatermark and pass an options object as shown below.

WebViewer({
  initialDoc: 'https://url/to/my_file.docx',
  // ...
}, viewerElement)
  .then(instance => {
    const { docViewer } = instance;

    docViewer.setWatermark({
      // Draw diagonal watermark in middle of the document
      diagonal: {
        fontSize: 25, // or even smaller size
        fontFamily: 'sans-serif',
        color: 'red',
        opacity: 50, // from 0 to 100
        text: 'Watermark'
      },

      // Draw header watermark
      header: {
        fontSize: 10,
        fontFamily: 'sans-serif',
        color: 'red',
        opacity: 70,
        left: 'left watermark',
        center: 'center watermark',
        right: ''
      }
    });
  });

watermark sample 1

linkDraw custom content as watermark

The setWatermark method also allows you to draw custom content on the page. To do this, pass a custom function to the API as a part of the options object.

For the following sample, we will use a Promise which will resolve with the watermark options object. If the document hasn't been loaded yet then DocumentViewer will wait to finish loading it until the watermark options are ready.

WebViewer({
  initialDoc: 'https://url/to/my_file.docx',
  // ...
}, viewerElement)
  .then(instance => {
    const { docViewer } = instance;
    const path = '/samples/full-apis/TestFiles/butterfly.png'

    // Promise resolves with options object
    const promise = new Promise(resolve => {
      const img = new Image();
      const options = {
        footer: {
          fontSize: 15,
          fontFamily: 'sans-serif',
          color: 'red',
          opacity: 70,
          left: 'left watermark',
          center: 'center watermark'
        },
        custom: (ctx, pageNumber, pageWidth, pageHeight) => {
          // the pageNumber is also passed in so you could have
          // a different watermark for each page
          ctx.drawImage(
            img,
            pageWidth / 2 - img.width / 2,
            pageHeight / 2 - img.height / 2
          );
        }
      };
      img.onload = () => { 
        return resolve(options);
      };
      img.src = path;
    });

    docViewer.setWatermark(promise);
  });

watermark sample 2

linkDraw watermark text in custom positions

The setWatermarkcustom argument can also be used to draw text in custom positions.

WebViewer({
  // ...
}, viewerElement)
  .then(instance => {
    const { docViewer } = instance;

    docViewer.setWatermark({
      custom: (ctx, pageNumber, pageWidth, pageHeight) => {
        // ctx is an instance of CanvasRenderingContext2D
        // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
        // Hence being able to leverage those properties
        ctx.fillStyle = '#ff0000';
        ctx.font = '20pt Arial';
        ctx.globalAlpha = 0.4;
    
        ctx.save();
        ctx.translate(0, pageHeight / 2);
        ctx.rotate(-Math.PI / 2);
        ctx.fillText('left side watermark', 0, 0);
        ctx.restore();
    
        ctx.save();
        ctx.translate(pageWidth, pageHeight / 2);
        ctx.rotate(Math.PI / 2);
        ctx.fillText('right side watermark', 0, 0);
        ctx.restore();
      },
    });
  });

watermark sample 3

linkDraw watermark without DocumentViewer

If you're constructing your own Document instance then it also provides a setWatermark method.

const filePath = '/webviewer-demo.pdf';
const watermarkOptions = {
 header: {
     fontSize: 15,
     color: 'blue',
     center: 'center watermark',
 },
 diagonal: {
     fontSize: 30,
     fontFamily: 'sans-serif',
     color: 'red',
     opacity: 100,
     text: 'Watermark'
 }
};

const doc = await CoreControls.createDocument(filePath, { l: 'Insert commercial license key here after purchase'});

// Set watermark options object
doc.setWatermark(watermarkOptions);

// Draw canvas
doc.loadCanvasAsync({
 pageIndex: 0,
 getZoom: () =>  0.8,  // 80% zoom,
 drawComplete: pageCanvas => {
   // Append canvas to dom to see the result
   document.body.appendChild(pageCanvas);
 },
});

linkDraw watermark dynamically

If you want to add a watermark or modify the existing watermark after pages are rendered, then after calling setWatermark you will also need to call the refreshAll and the updateView methods of DocumentViewer.

WebViewer(...)
  .then(instance => {
    const { docViewer } = instance;
    const watermarkOptions = {...};

    docViewer.setWatermark(watermarkOptions);
    docViewer.refreshAll();
    docViewer.updateView();

  })

If you are going to use a Promise then you need to call those two methods after the Promise has resolved:

WebViewer(...)
 .then(instance => {
   const { docViewer } = instance;
   const promise = new Promise(resolve => {
     // some asynchronous operations to generate the watermark options object
     resolve(watermarkOptions);
   });

   docViewer.setWatermark(promise);
   docViewer.getWatermark().then(() => {
     docViewer.refreshAll();
     docViewer.updateView();
   })
 })

Get the answers you need: Support

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.