Search code examples
canvaspdf.jspdfviewer

how to access canvas element when rendering a pdf using pdf.js


How to use the canvas element on which the PDF will be rendered using pdf.js. I am using viewer.js to render a pdf file in my webnsite. I want to use the canvas element on which the pdf gets rendered. how to do it. Can it be done using document.getElementById("mycanvas")???


Solution

  • PDF.js uses a one canvas per page it draws, the rest is of its UI is done using normal HTML code. The relevant part of the document tree looks like this:

    <div id="viewer">
      <a name="1"></a>
      <div id="pageContainer1" data-loaded="true">
        <div class="canvasWrapper">
          <canvas id="page1"></canvas>
        </div>
        <div class="textLayer" style="width: 604px; height: 453px;"></div>
        <div class="annotationLayer"></div>
      </div>
      <div id="pageContainer2" data-loaded="true">
      ....
    </div>
    

    So you can get an individual page canvas as document.getElementById("page" + page_num), or, maybe more robustly, via an xpath:

    //div[@id='viewer']//canvas[@id='page123']
    

    If you want to select all canvas elements, that's also easy with xpath:

    //div[@id='viewer']//canvas
    # or
    //div[@id='viewer']//canvas[contains(@id, 'page')]