Watermarks

An app using PSPDFKit can draw content on top of a PDF using the RenderPageCallback API. This API allows you to configure a callback that is executed with a reference to the page canvas. You can use it to draw additional information — watermarks, for example — on top of a PDF.

Using RenderPageCallback

Whenever a page is rendered or printed (only for PSPDFKit.PrintMode.DOM), you can use RenderPageCallback to render watermarks on the page.

To do this, define a Configuration#renderPageCallback function in which you execute your canvas drawing commands:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
PSPDFKit.load({
  renderPageCallback(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(
      `This is page ${pageIndex + 1}`,
      pageSize.width / 2,
      pageSize.height / 2
    );
  }
  // ...
});
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
PSPDFKit.load({
  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(
      "This is page " + (pageIndex + 1),
      pageSize.width / 2,
      pageSize.height / 2
    );
  }
  // ...
});

Within the callback, you have access to a CanvasRenderingContext2D and additional properties like the current pageIndex and the pageSize.

PDF page with a watermark

Make sure that the rendering commands are as efficient as possible, as they might be invoked multiple times per page (once per tile).

When you’re using the RenderPageCallback API to draw content on the page, the changes will only be visible on the client, and the exported PDF will not include these drawings. They will, however, be part of the printed page when using PSPDFKit.PrintMode.DOM.

Using Custom Overlay Items

Another approach to displaying arbitrary information on top of a PDF is the use of custom overlay items. This API allows you to place DOM nodes on top of the page.

In contrast to the RenderPageCallback API, the custom overlay items are, as the name suggests, overlaid, so it’s still possible for your users to unmask the underlying image. Custom overlay items also require more bookkeeping if you want to place them on top of every page, and they won’t be included in the printed page.

For a detailed guide on how custom overlay items work, please refer to our guide article.