In this example, we will learn how to access the canvas layer and draw an additional element on top of it.
To make it simple, we draw a string at the middle of top side of each page. To do so, we will create a plugin that handles the `onCanvasLayerRender`
event which is invoked when the canvas layer of page is rendered:
import { Plugin, PluginOnCanvasLayerRender, Viewer } from '@react-pdf-viewer/core';
const customCanvasPlugin = (): Plugin => {
const onCanvasLayerRender = (e: PluginOnCanvasLayerRender) => {
};
return {
onCanvasLayerRender,
};
};
The `PluginOnCanvasLayerRender`
event object consists of a few properties, but we will use the following
`status`
represents the rendering status `LayerRenderStatus`
. It can take one of two possible values:
Value | Description | From |
---|
`LayerRenderStatus.PreRender` | The viewer starts rendering the canvas | 2.2.0 |
`LayerRenderStatus.DidRender` | The canvas is rendered completely | 2.2.0 |
`ele`
represents the canvas element
`scale`
represents the current scale level
const message = "customer@email.com";
const onCanvasLayerRender = (e: PluginOnCanvasLayerRender) => {
if (e.status !== LayerRenderStatus.DidRender) {
return;
}
const canvas = e.ele;
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const fonts = ctx.font.split(' ');
const fontSize = parseInt(fonts[0], 10);
ctx.textAlign = 'center';
ctx.font = `${fontSize * e.scale * 4}px ${fonts[1]}`;
ctx.fillStyle = '#CCC';
ctx.fillText(message, centerX, 100);
};
As you see, the text `message`
is draw at the middle of top side using the Canvas APIs. In reality, you can draw a watermark or use a dynamic `message`
based on the current user.
Finally, we can create an instance of the plugin and registry it with the `Viewer`
component:
const customCanvasPluginInstance = customCanvasPlugin();
<Viewer
fileUrl={...}
plugins={[
customCanvasPluginInstance,
]}
/>