PHP allows you to generate PDF files dynamically, which can be useful for a variety of tasks. FPDF is a free PHP class containing a number of functions that let you create and manipulate PDFs.

PDFlib

The PHP API contains a number of functions for handling PDF files designed to be used with the PDFlib. Although extensive, this library is not free for commercial use. A free version called PDFlib Lite is available for personal use, but is limited in functionality. To use the full PDFlib library you must purchase a rather expensive license.

Why FPDF?

An alternative way of generating PDF files with PHP is using FPDF, a free PHP class containing a number of functions for creating and manipulating PDFs. The key word here is free. You are free to download and use this class or customise it to fit your needs. In addition to being free, it's also simpler to use than PDFlib. The PDFlib needs to be installed as an extension in your PHP package, whereas FPDF can just be included in your PHP script and it's ready to use.

Creating PDF files

To get started, you will need to download the FPDF class from the FPDF Web site and include it in your PHP script like this:

require('fpdf.php');

Below is an example of how you can generate a simple PDF using FPDF.

We begin by creating a new FPDF object with:

$pdf= new FPDF();

The FPDF constructor can take the following parameters:

|>String orientation (P or L) -- portrait or landscape
|>String unit (pt,mm,cm and in) -- measure unit
|>Mixed format (A3, A4, A5, Letter and Legal) -- format of pages

Next, we are going to set some document properties:

$pdf->SetAuthor('Lana Kovacevic');
$pdf->SetTitle('FPDF tutorial');

Because we want to use the same font throughout the whole document, we can set it before we create a page.

$pdf->SetFont('Helvetica','B',20);
$pdf->SetTextColor(50,60,100);

The SetFont function takes three parameters; the font family, style and size. We are using Helvetica, Bold and 20 points, which will be applied to the title of our document. You can either use one of the regular font families or set up a different one using the AddFont () function.

With SetTextColor () we are also setting the font colour for the entire document. The colours can be represented as RGB or grey scale. Here we are using RGB values.

Now that that's done, let's set up a page for our PDF document.

$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');

You can pass the AddPage () a parameter of "P" or "L" to specify the page orientation. I've used "P" for portrait. The SetDisplayMode function determines how the page will be displayed. You can pass it zoom and layout parameters. Here we're using 100 percent zoom and the viewer's default layout.

Now, that we've set up a page, let's insert an image to make it look nicer and make it a link while we're at it. We'll display the FPDF logo by calling the Image function and passing it the following parameters -- name of the file, the dimensions and the URL.

$pdf->Image('logo.png',10,20,33,0,' ','http://www.fpdf.org/');

You could have also inserted the link with:

$pdf->Link(10, 20, 33,33, 'http://www.fpdf.org/');

Now let's make a title for our document with a border around it.

$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,'FPDF Tutorial',1,0,'C',0);

The SetXY function sets the position of x and y coordinates, where we want the title to appear. SetDrawColor will set the colour of the border, using RGB values. After that's done, we call the Cell function to print out a cell rectangle along with the text of our title. We are passing the function the following parameters; width, height, text, border, ln, align and fill. The border is either 0 for no border or 1 for frame. For ln we are using the default value 0, "C" to centre align the text inside it and 0 for fill. Had we used 1 for fill the rectangle would have been coloured in. With a value of 0 we are making it transparent.

Now we want to write the main text to the PDF, that is display a little message.

$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,'Congratulations! You have generated a PDF. ');

Again we are setting the x and y positions of the text, but this time we are reducing the font size with the SetFontSize function. The write function will print the text to a PDF. The parameter 5 will set the line height. This is only relevant however, if there are multiple lines of text.

Finally we want to send the output to a given destination, using the Output function.

$pdf->Output('example1.pdf','I');

Here we are passing the function the name of the file and the destination, in this case "I". The "I" parameter will send the output to the browser.

Putting it all together:

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

//create a FPDF object
$pdf=new FPDF();

//set document properties
$pdf->SetAuthor('Lana Kovacevic');
$pdf->SetTitle('FPDF tutorial');

//set font for the entire document
$pdf->SetFont('Helvetica','B',20);
$pdf->SetTextColor(50,60,100);

//set up a page
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');

//insert an image and make it a link
$pdf->Image('logo.png',10,20,33,0,' ','http://www.fpdf.org/');

//display the title with a border around it
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,'FPDF Tutorial',1,0,'C',0);

//Set x and y position for the main text, reduce font size and write content
$pdf->SetXY (10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,'Congratulations! You have generated a PDF.');

//Output the document
$pdf->Output('example1.pdf','I');
?>

Now that you've learnt how to generate a simple PDF, let's see what else we can do with FPDF. The example code below demonstrates how to make a header and a footer for your document.


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

class PDF extends FPDF
{
  function Header()
    {
      $this->Image('logo.png',10,8,33);
      $this->SetFont('Helvetica','B',15);
      $this->SetXY(50, 10);
      $this->Cell(0,10,'This is a header',1,0,'C');
     }

  function Footer()
    {
      $this->SetXY(100,-15);
      $this->SetFont('Helvetica','I',10);
      $this->Write (5, 'This is a footer');
    }
}

$pdf=new PDF();
$pdf->AddPage();
$pdf->Output('example2.pdf','D');
?>


As you can see we are creating a child class of FPDF using inheritance and setting up the behaviour for both the Header and Footer functions. We then create a new object of this PDF class and add a page to our document. The AddPage () will automatically call the Header and Footer. Finally, we output it to a file called example2.pdf, this time using the "D" option for the sake of the example. This will send the file to the browser and open a dialog box, prompting the user to save the file.

Now that you have an understanding of how FPDF works, go ahead and play with some of its functions and have fun building your own PDFs. For the full list of functions, refer to the FPDF Web site.

Wide World of Web This was published in Wide World of Web, check every Wednesday for more stories

Comments

1

Struchkov Vladimir - 22/02/08

This article is nice. But many programmers can't use this library. This class doesn't suppurt for example cyrilic language. Look at this page http://acko.net/node/56. This is extension forf fpdf

» Report offensive content

2

Sean Falzon - 21/03/08

Personally a better option for generating PDF's is FOP

because FOP can output other formats not just PDF's you can cater for a broad range of requirements using the same templates.

also FPDF has not been updated in 4 years so that generally makes me wonder what happened to development.

» Report offensive content

3

me_great - 25/03/08

I want to convert a whole webpage into pdf using php.
Can you please help.

» Report offensive content

4

George - 03/05/08

HTML 2 FPDF > PDF would be nice. Usually one would like to think at a higher level, that is, tables (for example) with information in them and not cells. That way one could focus on the information to be presented instead of writing a custom rendering engine each time.

I have probably shot myself in the leg, I will go an read the manual now :)

» Report offensive content

5

mukti - 03/06/08

Good, but i have a question, how make a pdf file with a password?

» Report offensive content

6

Tim - 09/07/08

Any idea how much processing power it would take to generate a 300dpi .pdf file the size of an 8.5x11 piece of paper?

» Report offensive content

7

Ketan Patel - 17/07/08

Hi,

I use fpdf to generate pdf. it is working fine. but when i use session variables with it start problem .. IE need to refresh or retry to generate pdf...

» Report offensive content

8

ming_andrada - 30/07/08

hi, this one is really nice, i just got question here? about the logo.png, guys, where can i save it? and how can i call that image?

pls do give me ur answers...

thanks a lot...

» Report offensive content

9

Greegus Virere - 02/08/08

Ketan Patel > Mess with that one too... if you use output after calling session_start() page (in my case in opera) just stuck while loading. i "solved" the problem by putting script into new file without sessioning.

» Report offensive content

10

http://www.b2c-shopping.co.uk - 09/08/08

I am learn build pdf file these days, I want to read a excel file and export it to pdf, can PHP do this? thanks.

» Report offensive content

11

alto - 07/10/08

thanks for the big help

» Report offensive content

12

Viji - 14/10/08

Hi this example is nice. I want to set a background color for a cell. Can any one help me. Thanks in advance.

» Report offensive content

13

Muhammad Irshad - 25/10/08

i am new user of fpdf. so hopes well experience of using fpdf

» Report offensive content

14

Simi - 03/11/08

Helo.
i want to save pdf files frequently on my hard disk.file names and folders should be automatically generated.Iam using fpdf to generate pdf files.but data is not written into the disk proerly..is there anyone to solve my problem

» Report offensive content

15

blight - 07/11/08

FPDF is nice, ezPDF is useful also. You can check out some sample code at zedwood.com's http://www.zedwood.com/article/136/generate-pdfs-with-php article.

» Report offensive content

16

Shapon - 22/11/08

I want to make a document to pdf. How it possible . please write a document code and supporting php script code of this document. Urgent please!

» Report offensive content

17

Diverman - 16/01/09

Hi, im diverman from diverhaus.com, when i want to add text near the bootom of the page, it jumps to another page. making a single page in 3 or 4. just a new page for line of text, and its not even near the low part of the page??? so i cannot put text in that part. anybody knows whats happening? thanks and nice fpdf !!

» Report offensive content

18

Chris - 23/01/09

How would you change the color of a font midway through the output? For example, in this line:
$this->Cell(0,10,'This is a header',1,0,'C');

How would you change the color of the word "header" to blue?

» Report offensive content

19

Jay - 07/04/09

Hi, I am new user of pdf, I want to make a background image for html 'table' or 'td', is this possible,please...... How?

» Report offensive content

20

hozefa - 08/05/09

hi i am getting align ment problem in ezpdf when i am picking data from the table and if the content r more it automatically shift into next cell instead on new line
tried align=justification but did notwork plz helpme

» Report offensive content

21

ajit - 09/06/09

Hi i am getting problem in fpdf with string display.i trying to create dynamic pdf but in that string is not display propely it is having multiple sapce please give any solution

» Report offensive content

22

butterfly - 10/06/09

how to print online form in pdf format? what is the code should i use?

» Report offensive content

23

Rahul Anand - 25/07/09

Hi ! Really Nice Article. But can you send me the link from where I can download the whole code so that I can use that according to my requirements.


Thanks

Rahul Anand

» Report offensive content

24

Shantan - 06/08/09

Really nice tutorial.I am having problem in saving files to a local disk when i gave 'F' in Output() function in fpf.php.

case 'F':

//Save to local file

$f=fopen($name,'wb');

if(!$f)

$this->Error('Unable to create output file: '.$name);

fwrite($f,$this->buffer,strlen($this->buffer));

fclose($f);

break;

» Report offensive content

25

marjune - 07/08/09

hey i cant figure it out pls help, i downloaded the fpdf file then i copy the code above as my first try but my output like this


body {font-family:"Times New Roman",serif} h1 {font-size:150%; color:#4000A0} h2 {color:#4000A0} h3 {font-size:100%; margin-top:1.2em} dl.param dt {text-decoration:underline} dl.param dd {margin-top:1em; margin-bottom:1em} dl.param ul {margin-top:1em; margin-bottom:1em} tt, code, kbd {font-family:"Courier New",Courier,monospace; font-size:82%} div.source {margin-top:1.4em; margin-bottom:1.3em} div.source pre {display:table; border:1px solid #24246A; width:100%; margin:0em; font-family:inherited; font-size:100%} div.source code {display:block; border:1px solid #C5C5EC; background-color:#F0F5FF; padding:6px; color:#000000} div.doc-source {margin-top:1.4em; margin-bottom:1.3em} div.doc-source pre {display:table; width:100%; margin:0em; font-family:inherited; font-size:100%} div.doc-source code {display:block; background-color:#E0E0E0; padding:4px} .st {font-weight:bold; color:#900000} .kw {color:#000080; font-weight:bold} .str {color:#CC0000} .cmt {color:#008000} p.demo {text-align:center; margin-top:-0.9em} a.demo {text-decoration:none; font-weight:bold; color:#0000CC} a.demo:link {text-decoration:none; font-weight:bold; color:#0000CC} a.demo:hover {text-decoration:none; font-weight:bold; color:#0000FF} a.demo:active {text-decoration:none; font-weight:bold; color:#0000FF}
Fatal error: Class 'FPDF' not found in C:\wamp\www\mhee\sample.php on line 5

pls help

» Report offensive content

26

kstan - 03/10/09

Hi All,
My company'd just develop an open source PHP report library which allow you design PDF report via Java based IReport report designer. When you run the report it will use FPDF library as foundation and convert ireport xml file to PDF on the fly.

We make use the FPDF library but you can increase the productivity 100%-300% if you know how to use iReport.

Since my company gain a lot of benefit from open source software, so we willing to contribute something to open source community.
This project is free to use and free to change, project name = PHPJasperXML.

Download at:
http://www.simit.com.my/?q=phpjasperxml

This is new library and we need you feed back. Please feed back at:
http://www.extraknowledge.org/forum/viewforum.php?f=23

I'm not active in at here, please reply this message at forum aboved. Sorry I'm not promoting my forum, simply this forum is special for our company product & services, I check it always.

Below is the sample source code for display the report. Hopefully this project can spread fast, so that not PHP expert can design their PDF report easily.

Thanks for you trying this library.
Ks Tan

<?php

include_once('class/fpdf/fpdf.php');
include_once("class/PHPJasperXML.inc");
include_once ('setting.php'); //optional, just wanna to preset variable for database



$xml = simplexml_load_file("sample1.jrxml");


$PHPJasperXML = new PHPJasperXML();
$PHPJasperXML->arrayParameter=array("parameter1"=>1);
$PHPJasperXML->xml_dismantle($xml);

$PHPJasperXML->transferDBtoArray($server,$user,$pass,$db);
$PHPJasperXML->outpage("I"); //page output method I:standard output D:Download file


?>

» Report offensive content

27

Jimmy Man - 06/01/10

How can i see the demo for it?

» Report offensive content

28

Anes P.A - 01/02/10

Hi pals,
I am really Tired in using pdflib , my need is i need to put my Description field next line when that column length is greater than
55. I use PDF_add_cell for make a row of data. I use PDF_add_textflow , but I cannot get any thing in Generated PDF(all data Go out). How this Problem Can Rectify , pls help me as early as possible....

You can mail me
anes.pa@amskape.com

Regards
Anes P.A

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

28

Anes P.A - 02/01/10

Hi pals, I am really Tired in using pdflib , my need is i need to put my Description field next ... more

27

Jimmy Man - 01/06/10

How can i see the demo for it? ... more

26

kstan - 10/03/09

Hi All, My company'd just develop an open source PHP report library which allow you design PDF report via Java based IReport ... more

Log in


Sign up | Forgot your password?

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!