PDF.js is a Portable Document Format (PDF) viewer that is built with HTML5.
PDF.js is community-driven and supported by Mozilla Labs. Our goal is to create a general-purpose, web standards-based platform for parsing and rendering PDFs.
Benefits
The traditional approach to rendering PDFs in a browser is to use a native-code plugin, either Adobe’s own PDF Reader or other commercial renderers, or some open source alternative (e.g. poppler). From a security perspective, this enlarges the trusted code base, and because of that Google’s Chrome browser goes through quite some pain to sandbox the PDF renderer to avoid code injection attacks. An HTML5-based implementation is completely immune to this class of problems.
File Layout Overview
If you want to open a PDF from your website with PDF.js, simply link to the viewer and pass the location of the PDF file. For example:
1 | <span class="pl-ent">a</span> <span class="pl-e">href</span>=<span class="pl-s"><span class="pl-pds">"</span>/web/viewer.html?file=%2Fyourpdf.pdf<span class="pl-pds">"</span></span>>Open yourpdf.pdf with PDF.js</<span class="pl-ent">a</span> |
Firefox Browser
PDF.js is built into version 19+ of Firefox, however the extension is still available.
Chrome Browser
The official extension for Chrome can be installed from the Chrome Web Store.
This extension is maintained by @Rob–W.
Rendering the Page
Each PDF page has its own viewport which defines the size in pixels(72DPI) and initial rotation. By default the viewport is scaled to the original size of the PDF, but this can be changed by modifying the viewport. When the viewport is created an initial transformation matrix will also be created that takes into account the desired scale, rotation, and it transforms the coordinate system (the 0,0 point in PDF documents the bottom-left whereas canvas 0,0 is top-left).
1 2 3 4 5 6 7 8 9 10 11 12 13 | var scale = 1.5; var viewport = page.getViewport(scale); var canvas = document.getElementById('the-canvas'); var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext); |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Technology