How to create pdf files in php

In this tutorial, I will show you how you can create pdf files using php and a php class called fpdf.

This tutorial is only for making mysql tables appear in pdf files. So basically, its like creating a report for a certain project.

Let’s begin by downloading fpdf from their site.

After that, extract the fpdf folder into your project file in the ‘www’ folder  if you’re using wamp. And ‘htdocs’ if you’re using xampp.

Like this:

www>project_folder>fpdf

htdocs>project_folder>fpdf

If you’re going to browser through the fpdf site. And go to scripts, you will see a ready-made php scripts to generate reports from a mysql database. I just copied the code below from the site:

mysql_table.php:

<?php
require('fpdf.php');
 
class PDF_MySQL_Table extends FPDF
{
var $ProcessingTable=false;
var $aCols=array();
var $TableX;
var $HeaderColor;
var $RowColors;
var $ColorIndex;
 
function Header()
{
    //Print the table header if necessary
    if($this->ProcessingTable)
        $this->TableHeader();
}
 
function TableHeader()
{
    $this->SetFont('Arial','B',12);
    $this->SetX($this->TableX);
    $fill=!empty($this->HeaderColor);
    if($fill)
        $this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]);
    foreach($this->aCols as $col)
        $this->Cell($col['w'],6,$col['c'],1,0,'C',$fill);
    $this->Ln();
}
 
function Row($data)
{
    $this->SetX($this->TableX);
    $ci=$this->ColorIndex;
    $fill=!empty($this->RowColors[$ci]);
    if($fill)
        $this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]);
    foreach($this->aCols as $col)
        $this->Cell($col['w'],5,$data[$col['f']],1,0,$col['a'],$fill);
    $this->Ln();
    $this->ColorIndex=1-$ci;
}
 
function CalcWidths($width,$align)
{
    //Compute the widths of the columns
    $TableWidth=0;
    foreach($this->aCols as $i=>$col)
    {
        $w=$col['w'];
        if($w==-1)
            $w=$width/count($this->aCols);
        elseif(substr($w,-1)=='%')
            $w=$w/100*$width;
        $this->aCols[$i]['w']=$w;
        $TableWidth+=$w;
    }
    //Compute the abscissa of the table
    if($align=='C')
        $this->TableX=max(($this->w-$TableWidth)/2,0);
    elseif($align=='R')
        $this->TableX=max($this->w-$this->rMargin-$TableWidth,0);
    else
        $this->TableX=$this->lMargin;
}
 
function AddCol($field=-1,$width=-1,$caption='',$align='L')
{
    //Add a column to the table
    if($field==-1)
        $field=count($this->aCols);
    $this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align);
}
 
function Table($query,$prop=array())
{
    //Issue query
    $res=mysql_query($query) or die('Error: '.mysql_error()."<BR>Query: $query");
    //Add all columns if none was specified
    if(count($this->aCols)==0)
    {
        $nb=mysql_num_fields($res);
        for($i=0;$i<$nb;$i++)
            $this->AddCol();
    }
    //Retrieve column names when not specified
    foreach($this->aCols as $i=>$col)
    {
        if($col['c']=='')
        {
            if(is_string($col['f']))
                $this->aCols[$i]['c']=ucfirst($col['f']);
            else
                $this->aCols[$i]['c']=ucfirst(mysql_field_name($res,$col['f']));
        }
    }
    //Handle properties
    if(!isset($prop['width']))
        $prop['width']=0;
    if($prop['width']==0)
        $prop['width']=$this->w-$this->lMargin-$this->rMargin;
    if(!isset($prop['align']))
        $prop['align']='C';
    if(!isset($prop['padding']))
        $prop['padding']=$this->cMargin;
    $cMargin=$this->cMargin;
    $this->cMargin=$prop['padding'];
    if(!isset($prop['HeaderColor']))
        $prop['HeaderColor']=array();
    $this->HeaderColor=$prop['HeaderColor'];
    if(!isset($prop['color1']))
        $prop['color1']=array();
    if(!isset($prop['color2']))
        $prop['color2']=array();
    $this->RowColors=array($prop['color1'],$prop['color2']);
    //Compute column widths
    $this->CalcWidths($prop['width'],$prop['align']);
    //Print header
    $this->TableHeader();
    //Print rows
    $this->SetFont('Arial','',11);
    $this->ColorIndex=0;
    $this->ProcessingTable=true;
    while($row=mysql_fetch_array($res))
        $this->Row($row);
    $this->ProcessingTable=false;
    $this->cMargin=$cMargin;
    $this->aCols=array();
}
}
?>

That is long indeed, but we only need to understand one task that it does. For me, it basically takes care of all the formatting and page rendering for all the pdf files that were going to create, so we won’t have to have long lines of codes like this if we are now going to generate the actual page.

The code below would be the actual php script that will generate the page. In firefox 3.6 there’s no built in functionality that would render the pdf file on the actual page. So I recommend using chrome, so you won’t have to download a pdf file everytime you try to test it.

All you have to do now is to:

  1. import the mysql_table.php
  2. include your database server information. Stuff like server name, username and password.
  3. the actual query that would produce the report

 

pdfgeneratingpage.php:

<?php
 
require('mysql_table.php');
 
class PDF extends PDF_MySQL_Table
{
function Header()
{
 
    $this->SetFont('Arial','',18);
    $this->Cell(0,6,’All Products’,0,1,'C');
    $this->Ln(10);
 
    parent::Header();
}
}
 
mysql_connect('localhost','root','');
mysql_select_db('onstor');
 
$pdf=new PDF();
$pdf->AddPage();
 
$pdf->Table(‘SELECT * FROM prod_table’);
 
$pdf->Output();
?>

After you have done all of that, the generated page will now look something like this, if ever you try to access the ‘pdfgeneratingpage.php’ or whatever name you gave to your script:

image

 

Some points you have to check if ever it didn’t work out for you:

  1. Check the include or require function. You must include the actual directory where the ‘fpdf.php’ or ‘mysql_table.php’. Don’t just copy and paste, try to examine everything before complaining that it doesn’t work. Keep in mind the ‘..’ symbol is used to indicate that you’re going to move backwards. So if the file you’re trying to require/include is not in the same directory then try that.
  2. Check your database server information.
  3. Check your query in the mysql console first or in the phpmyadmin before putting it into your script, there might be some errors in your query.

Other than that I cannot see any reason why it wouldn’t work for you. So thanks for reading.

10 thoughts on “How to create pdf files in php

  1. hello kyokasuigetsu25,
    the script get printed as like:

    {rtf1ansiansicpg1252deff0deflang1033{fonttbl{f0fswissfcharset0 Arial;}} {*generator Msftedit 5.41.15.1515;}viewkind4uc1pardf0fs20 SetFont(‘Arial’,”,18);par $this->Cell(0,6,rquote All Productsrquote ,0,1,’C’);par $this->Ln(10);par par parent::Header();par }par }par par mysql_connect(‘localhost’,’root’,”);par mysql_select_db(‘db’);par par $pdf=new PDF();par $pdf->AddPage();par par $pdf->Table(lquote SELECT * FROM browserviewrquote );par par $pdf->Output();par ?>par par }

    when i executed the above code ………………

    can u figure out the pbm….. waiting for ur reply……… thanks in advance

  2. hay i am using this code…and when i click to the button it shows empty PDF file….it not showing a single page…but showing up result that page 1 OF 3…with no data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s