Choosing the right PDF library in PHP

Generate pdf files with PHPThere are a number of PDF libraries that can help you dynamically generate .PDF files through PHP : FPDF, TCPDF, DOMPDF, CEZPDF…

I’ve long worked with FPDF which is very light (with a core file of 49ko), easy to implement but the functions provided are limited.

TCPDF first astonished me since it is able to display pure HTML in a pdf file (tables, css,… support). It also provides transformation functions that allow you to display text vertically on a .pdf file, for example. But the TCPDF core file is much too heavy : 963 ko. I run AJAX scripts that load that library at each AJAX call, which makes the time waiting for the .pdf files to be ready much too long. So, I’ve tried to make that class lighter and got rid of all comments it contained. But I still had more than 500ko of file.

I then decided to go back to FPDF and found an extension class that allows FPDF to rotate text on a page.

This tutorial is devoted to implementing FPDF (and rotation class) in PHP framework Codeigniter 2.0.3.

First download the FPDF class. You’ll find it in the download page of http://www.fpdf.org. Along with the fpdf.php class, you’ll find tutorials and docs in the downloaded file

Simply copy the file fpdf.php to /Codeigniter_2.0.3/application/libraries/ and copy the font/ directory to /Codeigniter_2.0.3/application/third_party/fpdf/

Then go to http://www.fpdf.org/fr/script/script2.php where you’ll find two classes you’ll copy in the same libraries directory:

  • The FPDF_Rotate class as an extension of the FPDF class
  • The PDF class as an extension of the FDPF_Rotate class

Be careful when creating those two libraries in Codeigniter to follow Codeigniter’s tips on creating libraries. You’ll find the files attached to the bottom of this tutorial.

You’ll also have to define the path to the FPDF font directory in /Codeigniter_2.0.3/application/config/config.php :

//FPDF FONT DIRECTORY
$config['fonts_path'] = APPPATH.'third_party/fpdf/fonts/';

Then, in your controller, simply call the library and set the necessary items :
define('FPDF_FONTPATH',$this->config->item('fonts_path'));
$this->load->library(array('fpdf','fpdf_rotate','pdf'));
$this->pdf->Open();
$this->pdf->SetFont('Arial', '', 12);
$this->pdf->SetDrawColor(0);
$this->pdf->RotatedText(10,40,'Hello World!',90);
$this->pdf->MultiCell(100,5,"Test\nSecond line");
$this->pdf->Output('./pdfs/test.pdf', 'F');

You can download the necessary files : fpdf class files

Webliography :

FPDF Class

TCPDF

DOMPDF

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>