Archive

Posts Tagged ‘pdf templates’

PHP and PDF Templates

November 26th, 2008

Recently I had to write a class that could generate PDF payslips. Going for the easy option I wanted to take the existing template to re-use it and overlay the text from the database onto the template rather than redraw the entire payslip layout (which is just simply time consuming in PHP).

My chosen PDF library is FPDF so my first attempt was to create a graphic (png/jpeg) of the existing template and use the Image() function in FPDF to add the image to the PDF. However, this didn’t work as well as I’d have hoped since the image became very blurry. I believe this is due to the image being output at 72dpi onto the PDF when it actually needs greater resolution to be usable.

Obviously a better solution was needed, enter FPDI which allows you to load a PDF file as a template. So now all I needed to do was use the payslip PDF as a template and just overlay the text onto the template. FPDI makes this extremely simple – just include the required class file and do the following:-

$pdf = new FPDI();
$count = $pdf->setSourceFile("payslip-template.pdf");
$template = $pdf->import(1, "/MediaBox");
$pdf->addPage();
$pdf->useTemplate($template);

Now all you have to do is populate your content into/over the template and output it as normal.

One caveat I did notice was that FPDI seemed to be sending the files out with the mime type “application/x-download” rather than “application/pdf” which caused my browser to not know what to do with the file if I chose to open it rather than save it. My solution was to reset the Content-type header after outputting the PDF by taking advantage of existing output buffering in my application:-

ob_clean();
$pdf->Output("payslip.pdf", "D");
header("Content-type: application/pdf");
exit;

This works because output buffering allows us to change the headers that have already been output. If you do not currently have output buffering enabled in your code change the “ob_clean();” line to “ob_start();”.

FPDI is released under the Apache Software License, Version 2.0 which is compatible with the GNU GPL Version 3.

Coding , ,