Add Watermarks to PDFs Using JavaScript

PSPDFKit for Web allows you to render a watermark on top of your PDF content when it’s displayed to a user. This can be a useful technique for preventing screenshots by watermarking the document with personal information — for example, the user’s username.

To do this, provide a callback function to the renderPageCallback option for the pspdfkit#load() method.

This function will be passed a Canvas API context object, the page index, and the page size.

Now, using the Canvas APIs, you can draw your own watermark. In the example below, you can see how to render a watermark with the details of the user in the center of each page:

PSPDFKit.load({
  document: document,
  renderPageCallback: function (ctx, pageIndex, pageSize) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(pageSize.width, pageSize.height);
    ctx.stroke();

    ctx.font = "30px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.textAlign = "center";

    ctx.fillText(
      `Generated for John Doe. Page ${pageIndex + 1}`,
      pageSize.width / 2,
      pageSize.height / 2
    );
  }
});

Please note that this watermark is only rendered in the browser and has no impact on the PDF document itself.