How to do pdf password protected in node js

Today i have a requirement in my node js project to do pdf password protect. So any one open that pdf he must be enter password then he can view the pdf content. I am doing a lots of googling but i didn't get the proper solution of it. There is no module of node which i can use to protect my pdf. So finally i write a command and i execute it in node js. Actually this is a very easy after writing few lines you can do it. Below is my code and method of uses.

This is my code :

var exec = require('child_process').exec;
var pdfsourcepath = '../client/app/loanpdf/loan_21213131.pdf'; // This is pdf path with pdf name with out encription.
var pdfdestinationpath = '../client/app/loanpdf/loan_encripted_21213131.pdf'; // This is encripted pdf path with pdf name.
var password = "test123";  //This is your password to decript pdf.
var command = 'qpdf --encrypt '+password+' '+password+' 40 -- '+pdfsourcepath+' '+pdfdestinationpath;

exec(command,
function (error){
 if (error !== null){
 console.log('exec error: ' + error);
 }else{
console.log('Your pdf is encripted successfully.');
 }
}
);


Dependency of this code

1- You have to install qpdf first on your server by run this command 

sudo apt-get install qpdf

2- Don't forget to inclule the "child_process" library on the top of your file. By default is it comes with the bundled of node.js. So you don't need to install it.

var exec = require('child_process').exec;

Output of this code like below screen shot -


Pdf password protected in node js

If you having any problem while using this code or you like this post don't forget to leave a comment below i will reply you back with your.

Chears
Happy coding :)

2 Comments

  1. Hi,

    I am getting error as "'qpdf' is not recognized as an internal or external command,"

    Could you please help me.

    Thanks,
    Bala

    ReplyDelete
  2. Hi Bala,

    Thanks for your comment. Could you please show me example what exactly you are trying to do ?

    ReplyDelete
Previous Post Next Post