Last week, a friend of mine asked me to help him with a programming problem that he had been wrestling with for some time. The problem sounds simple:
- Take a PDF file
- Write something at the footer of each page of that file
And this had to be done with PHP.
Although there are several libraries available in PHP for dealing with PDF files, none seem to have capabilities to modify the contents of an existing PDF file. Their manuals/tutorials are full of examples on how to create PDF on the fly. After spending few fruitless hours trying to get the much recommended PDFLib installed in my Mac and have it work with MAMP, I painfully realized this library is for commercial use only. The free version leaves a horrible watermark of their site address on the generated PDF documents.
My search for a solution took me to FPDF, an open-source library for PDF file generation in PHP. In their FAQ section, I found the link to an extension of the library, named FPDI. This one was seemingly capable of ‘manipulating’ PDF files in an ad hoc fashion. It extracts the contents of each page in the file, uses it as a template, lets you put texts/shapes on the template and then outputs the modified file. Excited, I got into coding and after an hour of labor, finally succeeded to achieve my goal! Thank God for creating open source!
Enough talk, now lets get our hand dirty!
First we need to have following libraries downloaded and unzipped. They are just packages of PHP scripts that you just require/include in your own script. No need to deal with .dll/.so extensions.
Keep them in the same directory of your script, or in the include path. The following code snippet gives a basic idea of how to get started with it:
$pdf =& new FPDI();
//Set the source PDF file
$pagecount = $pdf->setSourceFile("my_existing_pdf.pdf");
//Import the first page of the file
$tpl = $pdf->importPage($i);
//Use this page as template
#Print Hello World at the bottom of the page
//Go to 1.5 cm from bottom
//Select Arial italic 8
//Print centered cell with a text in it
$pdf->Cell(0, 10, "Hello World", 0, 0, 'C');
The above code takes a PDF file “my_existing_pdf.pdf”, and creates a copy of it “my_modified_pdf.pdf” with “Hello World” printed at the centre bottom of the first page.
That’s it! To achieve my goal, which I outlined at the start of this post, I extended the FPDI class, and overrode the Footer() method to print a customized footer in each page.
I only wish that the PHP online manual did NOT have an entire section dedicated to PDFLib, a non-free and commercial library, and rather point to free ones such FPDF or TCPDF. It could have saved me hours.