How to view pdf documents using the pdf.js library

|
| By Webner

Introduction:

PDF.js is a library we can use to view pdf documents using javascript and HTML. This library comes handy in many scenarios such as showing a preview of a pdf document to the users when they upload it using the HTML <input type=”file” /> element. This way your users will be able to confirm their documents before uploading them to your website.

How to use:

You can use this library by using a cdn or if you are using a package manager in your project like npm then you can also install it using that. Below is the cdn for the pdf js javascript file:
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>

Example:
In this example, the user will first upload a pdf file using the Html <input /> tag and then we will preview it
using pdf js.

First import the necessary scripts in your Html file like this:

pdf.js library

Now, add the necessary Html elements under the body tag:

library

The user will choose the file using the input tag and the pdf will be shown in the canvas.
After this, add the necessary code for initializing the pdf worker in your javascript code like this:

pdf

Now, let’s preview the pdf using some javascript code like this:

js

In the above script, an event listener will load the pdf in the canvas when the user uploads a file using the HTML <input /> tag. The result should be something like this:

code

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *