Getting Started With PDF Generation in PHP

PDFs are everywhere now a days. From documents to e-books to invoicing they are becoming a standard. Generating pdf from programming languages can be tricky, though there are libraries provided to ease up the task.

Now a days more and more web applications are requiring some form of document generation whether it be reports, stats or billing. In this tutorial we are going to get in the basics of generating a pdf using php.

Getting Started

This tutorials assumes you have basic a knowledge of php and have a server (WAMP is good) installed on your system. First go to to FPDF website and download the library. Then create a folder in the server’s root directory and name it pdf_project. Then extract the zip file you have downloaded in the project library and you should see a similar structure.

For now we are interested in the fpdf.php file and the font folder. Create a new php file called test1.php, in the pdf_project folder and add the following code.

<?php
require('fpdf.php');

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Times','I',16);
$pdf->Cell(0,10,'Yay TutToaster Rocks !!',0,1,'C');
$pdf->Output();
?>

That’s it, now enter the url of the project, for localhost – http://localhost/pdf_project/test1.php . The output will be in pdf format.

What happened here is –

  • First we have included the fpdf library in our file.
  • Then we have created a new instance of FPDF class.
  • After that since our pdf document is empty so we need to add a blank page to add the content in it.
  • Next we have set the page font. Here you should know that fonts need to be imported other than available fonts for use in pdf generation.
  • Finally we have created a cell with parameters width, height and content.
  • Then We will output it to the browser.

Always call the SetFont method before adding cells in header, body or footer else nothing will be printed.

Taking a closer look

Now we will see in detail some of the important functions of FPDF class.

1) FPDF()

FPDF is the basic constructor which creates an instance of the FPDF class. It accepts 3 parameter orientation , unit and size. By default page is of A4 size. You can extend the fpdf class to add your own functionality.

2) Cell()

For the first cell code is

$this->cell(100,10,"This is a cell with width 100 and height 10",1,1);

For the Second cell code is

$this->cell(0,20,"This is a cell with width 100 percent and height 20",1);

For the Third cell code is

$this->SetFillColor(123,245,132);
	$this->SetY(60);
	$this->cell(100,10,"This is a cell with background fill",1,1,'',true);

Cell also supports background fill, you can do that by calling the SetFillColor method which accepts RGB values. Now whenever the fill option is set to true it will fill it with the color mentioned previously. Default color is black.

Final cell series

 
          $this->cell(30,10,"Cells",1,0,'',true);
	  $this->cell(30,10," without",1,0,'',true);
	  $this->cell(30,10," line break",1,0,'',true);

If the line break option is set to 0 cells appear floating adjacent to each other.

A cell is a block in which text is added. It has many parameters, starting from width, height , text , border,position, alignment and fill. A cell with 0 width represents a block with 100% width. Below are examples which will give you a clear picture of how cells work.

Note: That if text is more than the width, it overflows. Width is used as reference for next cell to be aligned if no linebreak is given.

3) Output()

  • First is the name of the file. Applicable only when download occurs
  • Send is the type, when “D” is passed, the file is downloaded with the given file name. “F” option allows it to save on the local disk though usually not required. The other remaining options are “I” by default and “S” which sends the data as a string.

Finally after creating the data, we need to output it. That is done by Output() method. This method outputs the data and opens the file in the browser only. In many situations this is not desired. We want the pdf file to be downloaded. For that options are provided –

4) Line Break and positioning

You can explicitly give the line break options using Ln() function. This gives a line break with height equal to the height of the previous cell if no value is given. If you want to add data at a specified position you can do that by calling setX() and setY() method.

$this->cell(30,10," Cell",1,1);
$this->Ln();  //produces a line break...

$this->SetY(60);
 $this->cell(30,10," Cell at Y - 60",1,1); // produces a cell at 60 px from the top.

Extending the class

So far we have rounded up the basics. There are times when we need repetitive use of functionality. So we can extend the fpdf class to make our own class with those functions. For that we will create a basic class which outputs a simple table.

<?php

require('fpdf.php');

class SimpleTable extends FPDF
{
	function generateTable($no)
	{

		for($i=1;$i<=10;$i++)
		{
		   $this->cell(20,10,$no,1,0,"C");
		   $this->cell(20,10," * ".$i,1,0,"C");
		   $this->cell(20,10," = ".$i*$no,1,1,"C");
		}
	}
}

$pdf=new SimpleTable();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->generateTable(2);
$pdf->Output();
?>

As you can see here that when we have inherited the FPDF class and inherit all the methods and can directly invoke the subclass with our new functions.

Adding Header and Footer

FPDF allows you to add footers and headers into your file. Though the initial functions are empty you can extend the class and add your own functionality by overriding them.

<?php

require('fpdf.php');

class Example extends FPDF
{
	function Header()
	{

    $this->SetFont('Times','B',15);
    $this->Cell(0,10,'TutToaster',1,0,'C');
    $this->Ln(20);
	}

	function Footer()
	{

    $this->SetFont('Times','B',9);
	$this->SetY(-15);
    $this->Cell(0,10,'Copyright TutToaster',1,0,'C');
    $this->Ln(20);
	}
}

$pdf=new Example();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Output();
?>

Here as you can see we didn’t called the header and the footer explicitly. They are called internally.

Images

You can use images too, it is relatively easy and supports all format. The main parameters include file path, x coordinate, y coordinate, width, height.

$this->Image('test.png',10,10,200,300);

Adding New Font support

FPDF supports basic fonts, but what about when you need more fonts. FPDF provides a way to import external fonts. For this tutorial we will use Aller font, you can download it here. Follow the steps –

First we need to make a afm file for our font. You can get the utility that is ttf2pt1.exe here which does that.

Now paste the font you want to be converted here and open up command prompt.

Navigate to the folder where ttf2pt1.exe is extracted as well as your font is placed. Enter the following command

ttf2pt1 -a yourpath\AllerDisplay.ttf Aller

Since in this tutorial , I have used Aller display. You can use your font.

Execute it and we will have two files type created with the last name on command prompt we have given. We are interested in the file with the afm extension.
Now add the ttf and afm fonts to the project folder.

Now create a php file and add the following code. Call it once by entering its address in the url. Two files aller.php and aller.z will be created. Move them to the font folder.

<?php
require('font/makefont/makefont.php');
MakeFont('AllerDisplay.ttf','aller.afm');
?>

Now to use our new font, first we will call it and then use it like we use any other font.

<?php
require('fpdf.php');

$pdf=new FPDF();
$pdf->AddFont('Aller','','aller.php');
$pdf->AddPage();
$pdf->SetFont('Aller','',20);
$pdf->Cell(0,10,'Yay using Aller font with FPDF !!');
$pdf->Output();
?>

Note the path of the font’s php file is relative to the font directory.

Thats it Folks

Now you are equipped with basic knowledge to create full fledged applications that require pdf generation. Next week we will take it to a more advance level by creating a Invoice Management Application from scratch including its UI, styling and back-end.

Join Testking 1Y0-A17 course to learn php and other web applications. Download the latest Testking 000-152 tutorials and Testking 70-291 demos to learn how to generate pdh in php.

This entry was posted on Friday, May 21st, 2010 at 08:15 and is filed under Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Hi, I am Abhin from beautiful city of lakes Udaipur, India. When it comes to work, I have an obsessive compulsive disorder to do everything I find and most of the time, I end up doing nothing ;). UI/UE fascinates me.

About the author Published by Abhin

9 Responses »

  1. Great post! I have used fpdf before too, its a great bit of kit. I actually prefer using a command line HTML 2 PDF tool. You should search the net, there is some great little apps out there!

  2. @php answers thanks, command line tools are good but here we are talking about integrating php in web apps

  3. Fpdf.php is an excellent class for creating pdf files on the fly via php.

  4. Great post! I have used fpdf before too, its a great bit of kit. thanks for sharing

Trackbacks

  1. designfloat.com
  2. Getting Started With PDF Generation In PHP | Design Newz