If you’re using Zend Framework 2 (
beta 4 beta 5) and need to easily generate PDFs, and you’d like to generate those PDFs from an HTML template, then boy do I have some good news for you!
For those of you who have dealt with generating dynamic PDFs, you know how much of a pain in the ass it can be (e.g. dealing with x, y coordinates, word-wrap (or lack of), etc.). There are a few options out there, some paid, some free, but none of them are as nice as DOMPDF (simple API, powerful, and free).
The true power behind DOMPDF comes from rendering standard HTML/CSS files instead of having to write ugly and unmanageable code.
Excerpt from their usage docs:
/* $html rendered/set... */
$dompdf = new DOMPDF();
That’s it. That will take your HTML and stream a PDF file to the end-user. Awesome, right?
Ok, let’s bring this back around to ZF2. About a month or so ago I started using ZF2 beta4 for a new project that I’m working on and wouldn’t you know it, I have to generate PDF reports, receipts, etc. I had a choice; I could just drop in DOMPDF, ignore the conventions set by ZF2, and move forward with my work, or I could spend a little extra time and create a clean and elegant solution that my project, future projects, and the ZF2 community could benefit from.
What I came up with is DOMPDFModule. A drop-in 3rd-party module that wraps DOMPDF and takes full advantage of ZF2′s implementation of the ViewModel pattern.
class ReportController extends ActionController
public function monthlyReportPdfAction()
$model = new PdfModel();
That’s it. The proper headers and template rendering happens behind the scenes. If you’d like the browser to prompt the user where to save the PDF file, call:
$model->setOption('fileName', 'monthly-report'); // File will be downloaded as monthly-report.pdf).
But wait there’s more! The installation of DOMPDFModule couldn’t be any easier, utilizing the increasingly popular PHP Composer dependency manager via Packagist repository. See README.md for installation instructions.