Site icon Web Niraj

Dynamically Adding Passwords to PDFs using PHP

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.

Prerequisites

Using Composer (or by other means), you first need to install the following libraries from Setasign:

Installing the above libraries will also install setasign/fpdi.

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 $file). The output function then return the new generated PDF in various formats.

See the gist on github.

Examples

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 FPDF library):

See the gist on github.

Troubleshooting

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.

Exit mobile version