Rendering PDFs with pdf.js using HTML5 and JavaScript

The web is full of PDFs floating around out there. How many times have you tried to open a PDF file on a machine and not had the correct software installed? It can be very frustrating. For most users out there they already have the correct software installed to view PDFs, but as users move towards tablets or newer machines - they may not have it installed. Another issue is that often certain PDF readers and plugins don't support important PDF features - which is a bit of a problem if you want your website to be accessible to everyone out there and if you want all your users to have the same experience.

PDF.js Logo

A couple of clever guys over at Mozilla have thought about this and have come up with a genius way of displaying PDFs inside your browser using Javascript and HTML5. The code is available for download on Github. PDF.js is community-driven and supported by Mozilla Labs which means its good news for us as developers. In the long run this plugin is intended to render PDFs natively within Firefox itself and will eventually ship with Firefox. For now though, we can start using the power of this plugin within our applications today.

Here I am going to run through a simple implementation of PDF.js and show you how easy it is to use. First head on over to Github and download the latest code required to start developing.

Then create a web page and embed similar to the following page.

As you will notice, there is a file called HelloWorld.js in the HEAD tag of the code above. My HelloWorld.js file looks like the code below - but you can also include the code directly in your page instead of linking to the file externally.

I have created a simple demo page that showcases the features that PDF.js offers. Please click here to view.

When I was testing with different PDF files, I noticed that certain characters aren't quite supported yet. As this is still an experiment and a work in progress, I expect new developments and additions will be constantly added. Keep this in mind if you notice any irregularities when working with this.

Using PDF.js also brings a security improvement for our users. It uses only safe web languages and doesn’t contain any native code pieces attackers could exploit. The only disadvantage that I can think of when using this code is that it might not work on some older browsers, which either way they can still view the documents using a traditional PDF viewer. Hopefully a polyfill will arrive soon for older browsers. For further information take a look on Github and the PDF.js team's website.

Go ahead and start using PDF.js in your applications today!