I need to put a password protection to PDF files using ghostscript in php.
These files will be uploading to server using simple form (I don't need any help with this), but they won't have any protection at first. So I want to put password protection to them using exec function and ghostscript in it. But I couldn't find anywhere what ghostscript query should be like.
For example, I have a PDF file called File.pdf. I upload it and then I need to put protection to it and call it File_protected.pdf.
I was trying to do it like this but '.ps' file weights too much and there is no password in the final File_protected.pdf:
exec("gs -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=File.ps File.pdf");
exec("gs -dNOPAUSE -dBATCH -sPDFPassword=password -sDEVICE=pdfwrite -sOutputFile=File_protected.pdf File.ps");
OK so firstly you don't need to convert the file to PostScript. Ghostscript is perfectly capable of taking the PDF file as an input and producing a PDF file as an output, lots of people do this for many reasons.
However, you need to be aware that if you do this, Ghostscript isn't just 'stamping' the PDF file or something, it is fully interpreting it down to marking operations and then making a completely new PDF file which incorporates those marks. But if you were satisfied by converting to PostScript and back to PDF you should find this satisfactory, its actually better than doing that 2 step conversion.
Secondly, there is no 'PDFPassword' switch for the pdfwrite device, which is why its having no effect. There are 2 switches: -sOwnerPassword
and -sUserPassword
. You may also want to supply the -dPermissions
switch.
You should read the PDF reference manual to glean the details but in short the Owner can do anything to the file, the User is limited to the Permissions (which is a bit field). If you don't supply a User password then anyone can open the file (limited to Permissions) but you need to supply the Owner password to do anything which is not allowed by the Permissions. I suspect this is what you want to do but its up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With