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.
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/progress.total)*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.