How to Show a Loading Progress Bar in PDF.JS

In PDF.JS Tutorial 1 we discussed how PDF.JS can be used to show a preview of the PDF at upload time. The application can navigate pages of the PDF using PDF.JS APIs.

In Tutorial 2 we discussed how PDF.JS can be also open a password protected PDF.

In this tutorial we will discuss how we can implement a progress bar when PDF.JS loads the PDF.


Click on the button to load a PDF file from a given url :

Loading page ...

Codes for the demo are provided towards the end of this tutorial for download.

Showing a Progress Bar

PDF.JS accepts a callback function as the fourth parameter in PDFJS.getDocument API call for monitoring the loading progress of the PDF. This callback receives an object with the properties loaded and total, through which we can find the percentage of the PDF loaded. Once we get the percentage loaded, showing a progress bar in UI is easy.

PDFJS.getDocument({ url: pdf_url }, false, null, function(progress) {
	var percent_loaded = (progress.loaded/*100;
}).then(function(pdf_doc) {
	// success
}).catch(function(error) {
	// error

In case you are wondering, the second and third parameters are pdfDataRangeTransport and passwordCallback. You don't need them.

A point to note is that PDF.JS documentation mentions the progress callback parameter as deprecated. You will get a message in the console :

Deprecated API usage: getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument

However there is no clear documenation as to what the new method is, so as of now this method has to be used. (This is the official "documentation" of PDF.JS APIs)

I've not included the codes for the demo app in this tutorial as it was almost a copy of the demo app in Tutorial 1, the only addition being the progress loader. However you can download them below, and refer to the first tutorial for the explanation of rest of the codes.

Download Sample Codes

PDF.JS Tutorial - How to display a PDF with Javascript
How to Open a Password Protected PDF with Javascript using PDF.JS