Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDF.js render pdf with scrollbar

I use mozilla pdf.js. I have a code:

<canvas id="the-canvas"/>
function displayDocument(){
        PDFJS.getDocument(numberOdDocument[attachment]).then(function (pdfDoc_) {
            pdfDoc = pdfDoc_;
            renderPage(pageNum);
          });
    }
function renderPage(num) {
        pdfDoc.getPage(num).then(function(page) {
          var viewport = page.getViewport(scale, rotate);
          canvas.height = '900';
          canvas.width = '500';

          var renderContext = {
            canvasContext: ctx,
            viewport: viewport
          };
          var renderTask = page.render(renderContext);

          renderTask.promise.then(function () {
            pageRendering = false;
            if (pageNumPending !== null) {
              renderPage(pageNumPending);
              pageNumPending = null;
            }
          });
        });
    }

Now i see only one page in canvas tag, but I want add scrollbar to my canvvas, and I want change page with scroll. How can I do that?

like image 304
faszynski Avatar asked Jul 02 '15 13:07

faszynski


1 Answers

Allow scroll

First, create a parent div to encapsulate the canvas element :

<div>
 <canvas id="the-canvas"/>
</div>

Then, set a fixed size with a vertical scroll

<div style="width:650px;height:600px;overflow-y:scroll;">...</div>

Finally, you can set the scale you want using the variable "scale" but keep these original lines :

function renderPage(num) {
 pdfDoc.getPage(num).then(function(page) {
  var viewport = page.getViewport(scale);
  canvas.height = viewport.height;
  canvas.width = viewport.width;
  ...

Render all pages

Keep in mind, that render a lot of pages will take a bit of time but here is how to do it.

Idea : you need to render each page in a separate canvas element.

First, create dynamically the canvas element with a specific id during render :

<div id="pdf-viewer"></div>
...
function renderPage(num) {
 pdfDoc.getPage(num).then(function(page) {
  var canvasId = 'pdf-viewer-' + num;
  $('#pdf-viewer').append($('<canvas/>', {'id': canvasId}));
  var canvas = document.getElementById(canvasId);
  ...

Finally, call renderPage() for each page

function renderAllPages() {
 for (var i = 1; i <= pdfDoc.numPages; i++) {
  renderPage(i);
 }
}
like image 62
F2000 Avatar answered Nov 20 '22 09:11

F2000