In this tutorial, we are going to display a pdf file inside an html canvas object with the ability to select the text in the page.

  1. Create a new folder(“root folder” later in the text) called testpdfjsselection.
  2. Inside this folder run git clone https://github.com/mozilla/pdf.js.git to download the latest version of the PDF.js library.
  3. Put any pdf file you want inside the root folder(in the example below we’ll use “oasis.pdf”).
  4. In the root folder create a file called index.html with the following code:
<!DOCTYPE html><meta charset="utf-8">
<link rel="stylesheet" href="pdf.js/web/text_layer_builder.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="pdf.js/web/ui_utils.js"></script>
<script src="pdf.js/web/text_layer_builder.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<body>
  <div>
    <canvas id="the-canvas" style="border:1px solid black;"></canvas>
    <div id="text-layer" class="textLayer"></div>
  </div>
<script>
 
PDFJS.getDocument("oasis.pdf").then(function(pdf){
    var page_num = 1;
    pdf.getPage(page_num).then(function(page){
        var scale = 1.5;
        var viewport = page.getViewport(scale);
        var canvas = $('#the-canvas')[0];
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
 
        var canvasOffset = $(canvas).offset();
        var $textLayerDiv = $('#text-layer').css({
            height : viewport.height+'px',
            width : viewport.width+'px',
            top : canvasOffset.top,
            left : canvasOffset.left
        });
 
        page.render({
            canvasContext : context,
            viewport : viewport
        });
 
        page.getTextContent().then(function(textContent){
           console.log( textContent );
            var textLayer = new TextLayerBuilder({
                textLayerDiv : $textLayerDiv.get(0),
                pageIndex : page_num - 1,
                viewport : viewport
            });
 
            textLayer.setTextContent(textContent);
            textLayer.render();
        });
    });
});
</script>
</body>
</html>
  1. Inside the root folder start a local php server via php -S localhost:8080.
  2. Open http://localhost:8080 in your browser.

You should see the following output:

You might see that the first page of your PDF document is displayed in the canvas object. Notice that the text is also selectable as there are absolutely positioned div tags with plain text inside above all text strings. Now you may add the annotation feature using the fabric.js library. Or create a neat flipbook using turn.js. Then you can convert all this html pieces into a single pdf file using jsPDF.