Rendering PDF in HTML5 Canvas

pdf.js is an HTML5 technology experiment from Mozilla that explores building a faithful and efficient Portable Document Format (PDF) renderer using Canvas without any native code support. The goal of the project is to create a general-purpose, web standards-based platform for parsing and rendering PDFs, and eventually to release a PDF reader extension powered by pdf.js. Integration with Firefox is a possibility if the experiment proves successful.

One of the main advantages of rendering to Canvas is that you bypass any extra plugins required to render the PDF. A example PDF rendered using the Canvas element is shown below. (Note, the PDF will be only visible if your browser supports HTML5 Canvas.)

The following is a sample code to render the above PDF to a Canvas element.

PDFJS.getPdf('demo.pdf', function getPdfHelloWorld(data) {
  //
  // Instantiate PDFDoc with PDF data
  //
  var pdf = new PDFJS.PDFDoc(data);
  var page = pdf.getPage(1);
  var scale = 1.5;
 
  //
  // Prepare canvas using PDF page dimensions
  //
  var canvas = document.getElementById('the-canvas');
  var context = canvas.getContext('2d');
  canvas.height = page.height * scale;
  canvas.width = page.width * scale;
 
  //
  // Render PDF page into canvas context
  //
  page.startRendering(context);
});

The pdf.js project is still a work in progress; check the following more elaborate demo of pdf.js. There are still many glitches and rendering artifacts, but you will get a broad picture of the capabilities of pdf.js.



One thought on “Rendering PDF in HTML5 Canvas

Comments are closed.