The Problem
While working on several client & internal projects, we often ended up in a scenario where we needed to implement functionality to export HTML/CSS as PDF or send the PDF as an email, exporting a simple HTML table to a complex layout like invoices & reports. So we needed something simple & flexible to fit in these types of generic requirements.
The Challenge
Data can be dynamic & would be generated at the client end, which leaves us with less control at the server end. So technically, whatever HTML will be generated on the client end needs to be sent to the server for rendering the PDF. Simply sending HTML to the server would render a PDF, which would be unformatted without any structure, as we need to send or attach CSS too.
The?Beginning
We had an initial exposure to FPDF, hence, we thought to try our hand with it. After playing around, we realized it did not allow us to write HTML straight away to PDF, also what we needed was to have CSS formatting. Hence, we started searching and landed on jsPDF, but the problem of applying formatting was still standing as jsPDF didn’t allow attaching CSS. We tried finding a solution and were looking for something that allows us to pass HTML and CSS, which can then be rendered to PDF.
The Solution
After spending almost 2 days, we stumbled upon the mPDF PHP library and, looking at the documentation & few examples, we found that what we were looking for was mPDF. It not only allows passing HTML straight away but also attaches a separate CSS file, which then renders a beautiful PDF. The mPDF PHP library helps to generate PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements.
The Implementation
After finalizing on mPDF, we implemented the PDF export feature. Below is the code for implementing the same. Have a look!
[wpgist id=”3eb0296265931ddb4e84″ file=”index.php”]

Leave a Reply