post image

How to Open a Password Protected PDF with Javascript using 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.

PDF.JS being a complete PDF viewer also supports viewing of password protected PDFs. This means that your application can prompt the user for password of the PDF when trying to be viewed. On receiving the correct password the application can show the PDF to the user, or else show an error message.

This tutorial is an extension of Tutorial 1.

Viewing a Password Protected PDF

To open a password protected PDF with PDF.JS, pass a password parameter to the PDFJS.getDocument API call :

PDFJS.getDocument({ url: pdf_url, password: pdf_password })

You can catch the error when the user gives the incorrect password.

PDFJS.getDocument({ url: pdf_url, password: pdf_password }).then(function(pdf_doc) {
	// success
}).catch(function(error) {
	// incorrect password

	// error is an object having 3 properties : name, message & code

For normal PDFs that have no passwords you can pass an empty string as the password.

That's it. For opening a password protected PDF only this addition is required.