React PDF viewer

Example: Draw on top of the canvas layer

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 need to handle the onCanvasLayerRender event which is invoked when the canvas layer of page is rendered completely:

import Viewer, { CanvasLayerRenderEvent } from '@phuocng/react-pdf-viewer';

const onCanvasLayerRender = (e: CanvasLayerRenderEvent) => {
    // Invoked when the canvas layer is rendered


The CanvasLayerRenderEvent event object consists of a few properties, but we will use the following

  • ele represents the canvas element
  • scale represents the current scale level
const message = "";

const onCanvasLayerRender = (e: CanvasLayerRenderEvent) => {
    // `e.ele` is the canvas element
    const canvas = e.ele;

    // Get the canvas context
    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;

    // Calculate the font size
    const fonts = ctx.font.split(' ');
    const fontSize = parseInt(fonts[0], 10);

    // The text will be placed at the middle
    ctx.textAlign = 'center';

    // Set the font
    ctx.font = `${fontSize * e.scale * 4}px ${fonts[1]}`;

    // The text color
    ctx.fillStyle = '#CCC';

    // Draw the text
    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.

(The sample code)

/ 8