How to Use pdf.js

Chris picture Chris · Feb 17, 2012 · Viewed 158.4k times · Source

I am considering using pdf.js (an open source tool that allows embedding of a pdf in a webpage). There isn't any documentation on how to use it.

I assume what I do is make an html page with the script referenced in the header, and then in the body, I put some sort of function call with an array of the file name and location. Can anyone help me out here?

Answer

Treffynnon picture Treffynnon · Feb 17, 2012

There is documentation available on their github readme. They cite the following example code:

/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

//
// See README for overview
//

'use strict';

//
// Fetch the PDF document from the URL using promises
//
PDFJS.getDocument('helloworld.pdf').then(function(pdf) {
  // Using promise to fetch the page
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport(scale);

    //
    // Prepare canvas using PDF page dimensions
    //
    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    //
    // Render PDF page into canvas context
    //
    var renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    page.render(renderContext);
  });
});