In a recent project, I was asked to modify uploaded PDFs to dynamically insert a user specified password to keep files secure. To achieve this functionality, I made use of the
PDFI library from Setasign, and in particular, the
FpdiProtection class. This tutorial shows how this can be done.
Using Composer (or by other means), you first need to install the following libraries from Setasign:
Installing the above libraries will also install
Creating the Password Helper
To assist with password protecting PDFs, I created a helper Class called
PasswordProtectPDF, which you can find below. The
protect function handles importing each page from your source PDF (specified as
output function then return the new generated PDF in various formats.
Below are various examples of how the dynamically generated PDF can be handled, e.g. returning it to the browser or forcing the PDF to download to the user’s device. The following output types are available (via
I= Inline PDF
S= PDF as a string for you to handle manually (i.e. with manual headers to force inline rendering or download)
D= Forcing the PDF to download to the user’s device, using the second parameter as the filename.
F= Saving the PDF to the server as a file, using the second parameter as the file path and name.
The FPDF library may not be able to handle all types of files, for example, depending on the compression used in the source PDF. Wrapping the above examples in a
try..catch statement will help you catch any errors in generating the PDF.
The above example (lines 4-14) shows how compression errors can be caught and handled gracefully.
For anything else, feel free to leave a comment below and I’ll try and help.
If this (or any of my other tutorials) have helped you, please considering supporting me via Patron: