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.
fpdf-demo

First download FPDF Library from official website http://www.fpdf.org/

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.

require('lib/fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();

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

require('lib/fpdf/fpdf.php');
class PDF extends FPDF
{
	// Simple table
function BasicTable($header, $data)
{
    // Header
    foreach($header as $col)
        $this->Cell(40,7,$col,1);
    $this->Ln();
    // Data
    foreach($data as $row)
    {
        foreach($row as $col)
            $this->Cell(40,6,$col,1);
        $this->Ln();
    }
}
}

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'),
	         );
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->Output();

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.

DEMO

DOWNLOAD


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

Posted in: PHP

3 Replies to “Convert HTML to PDF using PHP FPDF Library”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.