Archive | PDF RSS feed for this section

Easy way to generate PDF in PHP

9 Oct

Working with PDF is really sticky. We need to calculate every pixel. And if we use ZEND LIBRARY arranging the layout is also a big issue. Recently I used FPDF (http://www.fpdf.org/) library it is really nice thing. [Thnx to HASIN BHAI  as he referd me to FPDF.]

Using  FPDF is really easy and fancy. For layout it use cells almost like table. Sot we can add text any where easily.

They have a good tutorial to learn it in a second. I am just describing their fired example
<?php
require(‘fpdf.php’);

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont(‘Arial’,’B’,16);
$pdf->Cell(40,10,’Hello World!’);
$pdf->Output();
?>

require(‘fpdf.php’);
In first line we how to include the PDF library.

$pdf=new FPDF();
This is the reference of the fpdf library.

$pdf->AddPage();
This instruction use to arrange the page layout. We can send some string parameter to define the page like ‘A4’ ‘L’ (Landscape) etc.

$pdf->SetFont(‘Arial’,’B’,16);
This line is use to define the font. But have to keep in mind that we need the font folder with font reference with script.

There are some  extra instruction like
$this->SetDrawColor(0,80,180); // Define the border color or graphics color
$this->SetFillColor(230,230,0);  //  The graphics or cell background color
$this->SetTextColor(220,50,50); // Text color.

To add image we can use a simple function  
$this->Image(‘logo_pb.png’,10,8,33);

Now to add text normally we use cell. This is a very commonly used function in FPDF with some parameter.
$pdf->Cell(20,10,’Title’,1,1,’C’,1);
First tow parameter means width and height. Third parameter is txt.
Fourth parameter define border. If we put 1 will enable border in all side. Also can send T for top, B for bottom, L for left and R for right. Let’s say we want to put border at top and left side then we have to write like this $pdf->Cell(20,10,’Title’,’LT’,1,’C’);
Fifth parameter defines the alignment. 0 for arrange after your current cell and 1 for put in new line.
Sixth parameter defines the text alignment.
Seventh parameter user for cell background must be 1 for colored or 0 for transparent. Default value: 0.

Now to send the PDF in output we user $pdf->output() function. If we want to  show in browser instantly just simply use  $pdf->Output(); and if we want to save as file then just enter the path in the function like $pdf->Output(‘/home/pub_html/text.pdf’);

Another on instruction we use frequently is $pdf->Ln() to go next line by force.

Advertisements