Generate PDF using PHP

In this post we will show you how to generate a PDF using PHP. We will be using FPDF, a PHP class, to generate the PDF. Generating PDFs using PHP is very easy. Let's start right away.

First of all you need to download the FPDF class. Its absolutely free . Go to their download page and download the latest version. Right now the latest version is 1.6 you can download it directly from here. Once you have downloaded the zip/tar file uncompress it. You will find a fpdf.php file and font folder inside it along with other files. Copy this fpdf.php file and font folder to your root directory where you will be writing the code. Now we are ready for the real thing! Check out the example given below -

 <?php

//Includes fdpf.php file

require('fpdf.php');


//New object of class FPDF declared

$pdf=new FPDF();


//New page added to the pdf

$pdf->AddPage();


//Font set to Arial bold 15

$pdf->SetFont('Arial','B',15);


/*Width and height of a cell along with the text it will contain*/

$pdf->Cell(40,10,'Hello World! This is my first PDF.');


/*Line break*/

$pdf->Ln();


/*Centre aligned cell*/

$pdf->Cell(200,20,'Tutorial by www.bOtskOOl.com',0,1,'C');


/*Line break*/

$pdf->Ln();


/*Image included :-) */

$pdf->Image("http://www.botskool.com/sites/default/files/logo.jpg");


/*Output sent to the browser*/

$pdf->Output();

?>

Screenshot of the generated pdf is shown below - 

Generate PDF using PHP

The code has been commented so that it can be easily implemented. A detailed explanation of the above code along with some other examples will be put up soon. 

 

Tags: