Friday, December 30, 2011

Creating Dynamic PDF files using PHP

Here, we are going to study on converting HTML 2 PDF using PHP. Here we are going to use free open source PHP scripts to accomplish this file conversion. So we will be using FPDF for this, as all Libraries are already written for this And well Optimize also in terms of PDF generation time & size.

FPDF: The PDF Generator


The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.



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

To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
$pdf=new FPDF('P','mm','A4');

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).


Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().


To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:



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

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:



$pdf->Cell(40,10,'Hello World !',1);

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.There are lot more functions in FPDF and we cannot cover all those in this article.
To learn FPDF, please browse http://www.fpdf.org.

No comments:

Post a Comment