While working on several client & internal projects we often landed up in a scenario where we need to implement functionality to export HTML/CSS as PDF or send the PDF as an email exporting simple HTML table to complex layout like invoices & reports. So we needed something simple & flexible to fit in these types of generic requirements.
Data can be dynamic & would be generated at client end which left us with less control at the server end. So technically whatever HTML will be generated on client end needs to be sent to the server for rendering PDF. Simply sending HTML to the server would render PDF which would be unformatted without any structure as we need send or attach CSS too.
We had an initial exposure to FPDF hence we thought to try our hands with it. After playing around we realized it did not allow to write HTML straight away to PDF, also what we needed was to have CSS formatting. Hence we started searching and landed to jsPDF but still 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.
After spending almost 2 days we stumbled upon mPDF PHP library and looking at the documentation & few examples we found what we were looking for was mPDF. It not only allows to pass HTML straight away but also attach separate CSS file which then renders beautiful PDF. mPDF PHP library help to generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements.
After finalizing on mPDF we implemented the PDF export feature. Below is the code for implementing the same. Have a look!