Render Watermarks in Our JavaScript PDF Viewer

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

ℹ️ Note: These rendered watermarks won’t be persisted to the document when saving.

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:

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,
		);
	},
	// ...
});

Within the callback, you have access to 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 won’t 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 detailed information on how custom overlay items work, please refer to the Creating Custom Overlay Items guide.