PHP might not be the most adequate language to generate documents, but in small projects, keeping things simple helps being on budget. So, I chose to look for a library to create the PDF documents required for a project.

First Approach

The first PDF documents I created with PHP were relatively simple. That’s why I opted to use HTML which I knew well.

My library of choice then was mPDF for its great HTML and CSS support. I could even reuse part of my existing HTML content, but still, it felt like I was building newsletters using old techniques, like tables to organize content. Not to mention that all existing libraries (mPDF, fPDF, TCPDF) feel outdated in a PHPMailer way. Considering the amount of work necessary to make a working PDF generator, I understand that those libraries are hard to maintain up to date with current standards. I wished they were more pleasant to use though.

Second Experience and Tactical Change

That aside, my next project was more demanding. The structure of the document was quite daunting. I started out with the same workflow as my previous project. After a few hours and little to no progress, I decided to search for a better solution online. It then occurred to me that I could use a PDF model as a base to generate my PDF.

And so, I set forth on my journey to find a solution that allowed me to use an existing PDF as a template to generate a new document. I could have used a background image as a simple solution, but then the text would not be selectable anymore.

There was a PDF importer included in mPDF, but to my dismay, it was left uncompleted in the repository. Spying some Stack Overflow subjects (1,2), I was lead to FPDI, a PDF importer which was made to work with fPDF, but can also be used with TCPDF. I chose to use fPDF because of its original support.

Here is an example of how it can be used:

//Load dependencies
//Import template
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('Fantastic-Speaker.pdf');
$tplIdx = $pdf->importPage(1, '/MediaBox');

$pdf->useTemplate($tplIdx, 10, 10, 90);

//Add your own stuff on top of the template


Closing words

For quick PDF generation, you might want to check out mPDF for its great CSS support which make styling easy. While for more complex documents, you might need to consider using FPDI to import a document to use as a template.