How to Enable Annotations in PDF.JS

This tutorial is an extension of the tutorial How to display a PDF with Javascript (which described how a PDF can be rendered in a HTML page using the PDF.js library and Javascript).

This tutorial show how you can enable the annotation layer in PDF.js, and show annotation data such as links. Rendered PDFs in which links can be clicked offer more value.

PDF.JS version 1.9 is used in the tutorial.


Loading document ...
Loading page ...

Download codes for the above demo

Step 1: Adding a <div> Element to Hold the Annotation Layer

<div id="annotation-layer"></div>

This div will hold the annotation data of a PDF page. The PDF will be rendered in a canvas.

<canvas id="pdf-canvas"></canvas>
<div id="annotation-layer"></div>

Step 2 : Adding CSS for Annotation Layer

Add the following CSS :

#annotation-layer { 
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    opacity: 0.2;
    line-height: 1.0;

#annotation-layer > section {
    color: transparent;
    position: absolute;
    white-space: pre;
    cursor: text;
    transform-origin: 0% 0%;

#annotation-layer > .linkAnnotation > a {
    position: absolute;
    font-size: 1em;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

Step 3: Getting the PDF Annotations

After the PDF has been rendered in the canvas, you need to get annotation data of the page, and then render that data in the annotation layer element.

The method getAnnotations() returns a Promise, which when resolved returns the annotations data for the page. PDFJS.AnnotationLayer.render() will render the data in the annotation layer div.

// page is the page context of the PDF page
// viewport is the viewport required in renderContext
// For more see    

page.render(renderContext).then(function() {
    // Returns a promise, on resolving it will return annotation data of page
    return page.getAnnotations();
}).then(function(annotationData) {
    // PDF canvas
    var pdf_canvas = $("#pdf-canvas"); 

    // Canvas offset
    var canvas_offset = pdf_canvas.offset();

    // Canvas height
    var canvas_height = pdf_canvas.get(0).height;

    // Canvas width
    var canvas_width = pdf_canvas.get(0).width;

    // CSS for annotation layer
    $("#annotation-layer").css({ left: canvas_offset.left + 'px', top: + 'px', height: canvas_height + 'px', width: canvas_width + 'px' });

    // Render the annotation layer
        viewport: viewport.clone({ dontFlip: true }),
        div: $("#annotation-layer").get(0),
        annotations: annotationData,
        page: page
How to Enable Text Selection in PDF.JS