Friday, May 8, 2015

Creating PDF Reports and Files in PHP


Hello everyone, how are you guys??
Sorry for my silence in past few days, had some projects and assignments to complete!

Well this article will focus on creating a PDF report or a PDF file using PHP.

So first of all we have to download the FPDF support library to generate PDF files. Visit  http://www.fpdf.org/ and go to downloads and download the latest version.

Well now we are ready to go.

Step 1 :- Import the library to our PHP file.
              include("includes/fpdf/fpdf.php");

Step 2 :- In order to use the functions in FPDF library we have to create a object of fpdf class.
                         $pdf = new FPDF('P','pt','A4');
 In here $pdf is our object name and P is for the page orientation, A4 is for page size.

Step 3 :- Now we have created the object and we have to open the pdf file.
                        //opening the pdf file
              $pdf->Open();

Step 4 :- Then add the first page of the PDF file.
                       //add the first page
             $pdf->AddPage("P","A4");

Step 5 :- Set the X and Y axis for the content in the PDF file
             //setting y axis through a variable
             $Yax = 30;
             $pdf->SetY($Yax);
             //setting X axis directly
             $pdf->SetX(40);



Well now, we have created our pdf file. Remember not to add PHP closing tag in the PDF generating code.

Lets see some functions that we can use to add some text and decorate them.

//setting title
$pdf->SetFillColor(234,44,234);
Above lines will add background color to the text.

//setting font $pdf->SetFont('Arial','B',25);
Above lines will define the font that we want our text to be printed in the PDF file

//adding the text to the pdf file $pdf->Cell(0,30,"Book Catalogue",0,1,"C",1);
Above lines will add the text or the line of text to the PDF file. 
$pdf->Cell(a,b,c,d,e,f,g);
a - X value of the position
b - Y value of the position
c - text that we want to print
d - border value of the text cell
e - line number
f - alignment of the text
g - indicates if the line cell background is filled(true,1) or not(false,0). Default value is false.

//adding more text to the pdf file(paragraphs)
$pdf->Write(0,"Error selecting values from database! ".mysql_error());
$pdf->Write(0,"your paragraph here");
Above lines will add text to pdf file.


At the end of the PHP code we have to add $pdf->Output(); function to make our PDF file visible. Without this function our PDF file will not be generated and printed to the screen.
Well hope you guys got some basic knowledge about generating a PDF file using PHP.
Comment box is open for your ideas, suggestions..
Thank You!

See you guys.. :)