Convert HTML to PDF using PHP FPDF Library

PHP based FPDF is very powerful library to convert your HTML pages or content into PDF file, Suppose you have a article and you want to add a button to download that article in PDF format for that case this library is very helpful, In other case if you want to create a reporting system for your big application like want to add a button to download all products summary in PDF file then this library is for you.

Here I’ll talk about the integration of this library in your project with some basic example.

First download FPDF Library from official website

After that unzip file and copy and paste FPDF library in your project library folder.

Call fpdf.php class where you want apply the PDF download feature, If you want to create PDF directly with HTML then see below official basic example.

$pdf = new FPDF();
$pdf->Cell(40,10,'Hello World!');

In the above example using SetFont() function you can set the font size and property for your PDF content.

Next Suppose you have a product list and you need to create a button by which you’ll able to download whole product list in PDF format then use below code.

Create a simple class and a method to generate table format in pdf content

class PDF extends FPDF
	// Simple table
function BasicTable($header, $data)
    // Header
    foreach($header as $col)
    // Data
    foreach($data as $row)
        foreach($row as $col)

After that call BasicTable() function where you want to generate product table in PDF format.

$pdf = new PDF();
$header = array('ID', 'Product Name', 'Price (Rs)');
$data = array(
	          array('1', 'Item-1', '5000'),
	          array('2', 'Item-2', '1200'),
	          array('3', 'Item-3', '1800'),

In the above example i just created a sample header and data in array format you can apply same thing in dynamic format to fetch data form your live database and sent it to BasicTable function to generate product pdf file.

See live demo and download source code.



If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Posted in PHP