PDF.JS How to make pdf-js viewer canvas responsive?

cAMPy picture cAMPy · Mar 14, 2016 · Viewed 12.4k times · Source

I have to display PDF using PDFJS library on my page. The problem is that since I give the scale as a fixed number canvas in which PDF is rendered is not responsive and does not fit the bootstrap grid column width. Here is HTML code:

<div class="row">
   <div class="col-md-1" style="padding-right: 15px;">
     <input type="button" ng-click="openPreviousPage()"/>
   </div>
   <div class="col-md-8">
     <canvas id="the-canvas" style="border: 1px solid black;"></canvas>
    </div>
    <div class="col-md-1 col-md-offset-2" style="padding-right:15px;">
      <input type="button" ng-click="openNextPage()" />
    </div>
</div>

and my Typescript in a controller:

 openPage = (pdf: PDFDocumentProxy, pageNumber: number) => {
        pdf.getPage(pageNumber).then(function getPage(page) {
            var scale = 1;
            var viewport = page.getViewport(scale);

            var canvas = <HTMLCanvasElement>document.getElementById('the-canvas');
            var context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;


            var renderContext = {
                canvasContext: context,
                viewport: viewport
            };

            //...rest of actions
        });
    }

Would be grateful for any hint.

Answer

Tony G. Bola&#241;o picture Tony G. Bolaño · Jun 17, 2016

You can put an id on canvas container div and set the scale based upon div.clientWidth and viweport.width.

On your HTML code:

<div class="row">
  <div class="col-md-1" style="padding-right: 15px;">
    <input type="button" ng-click="openPreviousPage()"/>
  </div>
  <div class="col-md-8" id="the-container">
    <canvas id="the-canvas" style="border: 1px solid black;"></canvas>
  </div>
  <div class="col-md-1 col-md-offset-2" style="padding-right:15px;">
    <input type="button" ng-click="openNextPage()" />
  </div>
</div>

Then on the controller:

openPage = (pdf: PDFDocumentProxy, pageNumber: number) => {
    pdf.getPage(pageNumber).then(function getPage(page) {
        var container = document.getElementById('the-container');
        var canvas = <HTMLCanvasElement>document.getElementById('the-canvas');
        var context = canvas.getContext('2d');

        var viewport = page.getViewport(1);
        var scale = container.clientWidth / viewport.width;
        viewport = page.getViewport(scale);

        canvas.height = viewport.height;
        canvas.width = viewport.width;


        var renderContext = {
            canvasContext: context,
            viewport: viewport
        };

        //...rest of actions
    });
}

Hope this helps...