When writing business web applications you often need to show PDF files in your application. But this requires that the user has an installation of a PDF viewer (e.g. Adobe Reader) and the browser plugin is activated. With PDF.js there is a chance to provide reliable and consistent PDF viewing capabilities in your application. This post provides some background information and shows how to integrate the PDF.js viewer into your own application.
Getting the PDF.js viewer
You can also take a pre-built version from the “gh-pages” branch of the GitHub project (the branch can be downloaded as zip file). But be aware that this version isn’t minified and therefore not as efficient as possible. If using the version from the “gh-pages” branch, you’ll need to put the folders “web” (excluding the example PDF file) and “build” into your own web application. These are only static files that need to be downloaded by the browser, so no special server-side technology is needed.
On the top of the file
web/viewer.js you can adjust several settings. One setting is the default PDF file that is shown if no other file is specified. This is set by default to a value that is useful for the demo hosted on the project’s web page. You should change this to a reasonable value or
about:blank to show nothing by default.
If you want the
pdf.worker.js files to be in a different location than the
build folder, you have to adjust two things:
pdf.js file is included in the
pdf.worker.js is included in the
PDFJS.workerSrc = '../build/pdf.worker.js';
Showing PDF files using the PDF.js viewer
This is my favorite part as it is almost trivial… Simply open the
web/viewer.html with a parameter
file set to the URL of your PDF file. An example URL could look like this:
As you simply show an html file, you are free to embed the PDF.js viewer as IFrame, popup or opening it as new window/browser tab.
Some more thoughts
As current versions of Google Chrome and Mozilla Firefox already natively support showing PDF files, it could be unnecessary to force the usage of the self-hosted PDF.js viewer as this results in additional files to be downloaded. As the PDF viewer included in Firefox is based on the PDF.js viewer, the user potentially won’t even see the difference. So a valid option to provide best and efficient support for the users is to use the built-in PDF viewer of the browser if you are sure one is available and only use PDF.js for uncertain cases (e.g. users with Internet Explorer).
But it could also be desirable to use PDF.js on all browsers to ensure a consistent look and behaviour for all users.
If you need to support Internet Explorer 8, you should provide a fallback for those users. For example you could use an IFrame directly pointing at the PDF’s URL. If the user has a PDF viewer, it will be used. If not the file can be downloaded by the user as last fallback.