* Required Fields
THANK YOU for contacting us

We endeavour to answer all enquiries within 1 business day, so you’ll be hearing from us shortly.

In the meantime we’d love you to get social with us
or perhaps you’d like to sign up to our newsletter?
You’ll receive FREE actionable tips and insights to improve your website



Create a Dynamic PDF with PHP (Tutorial)

29 Apr 2013

I have recently discovered a brilliant PHP library for creating PDF files. The library is FPDF. This tool allows you to create PDF documents with dynamic information.

Right, so how does it work?

Easy peasy - here's a basic tutorial for getting you started with building dynamic PDF documents with PHP.

Downloading the FPDF library

Go to www.fpdf.org to download the library files (Yes the website is UGLY but don't let that deter you!).
You should only need the file fpdf.php and the fonts library. This will need to be uploaded somewhere on your website's directory.

Setting up our PHP file

Create your PHP file and link to the FPDF library.

Set up some default values for your PDF Document:
// Create your class instance
$fpdf = new FPDF();
// Set up the default page margins for your PDF
// The parameters are margin left, margin top, margin right (units used are mm)
$fpdf->SetMargins(0, 0, 0);
// SetAutoPageBreak function will create a new page if our content exceeds the page limit. 0 stands for margin from bottom of the page before breaking.
$fpdf->SetAutoPageBreak(true, 0);
// AliasNbPages is optional if you want the ability to display page numbers on your PDF pages.

Link to the font files to access the fonts you want to use:
// We need to define the path to where our font files are located. To add additional fonts from the default ones supplied see http://www.fpdf.org/makefont/)
define('FPDF_FONTPATH', 'font/');
// Setting up our fonts and styles - The first parameter is the string you will use in your code to access this font, the second is the style of the font you are setting (B = bold, I = italic, BI = Bold & Italic) and finally is the php file containing your font.
$fpdf->AddFont('Verdana', '', 'verdana.php'); // Add standard Arial
$fpdf->AddFont('Verdana', 'B', 'verdanab.php'); // Add bolded version of Arial
$fpdf->AddFont('Verdana', 'I', 'verdanai.php'); // Add italicised version of Arial
FPDF comes with the standard fonts Courier, Helvetica/Arial, Times, Symbol & ZapfDingbats. So for these fonts, the above linking to the .php files isn't necessary.

Next we need to add our first page to the PDF - this is also used to add any additional pages.

Adding Text

To add text to our PDF we will be using the functions Cell and MultiCell.

Cell - This is where you have a set amount of text that can fit within a certain width and height.
MultiCell - This is more for when you might have a few lines of text that perhaps does not have a set amount of characters. So instead you set a height per line rather than full cell height, and then set a width for the text to display within.

For example, to code the following

Description: Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Suspendisse
iaculis quam nec nibh fringilla euismod.
Nam accumsan neque eget lorem
scelerisque vestibulum.

We would use both functions Cell and MultiCell. We will need to set our font size and define which font we are using before using our functions.

// Set font size
// Select our font family
$fpdf->SetFont('Helvetica', '');
// Now we use the Cell function
$fpdf->Cell(56, 6, 'Description', 0, 0, 'L', FALSE);
/* Parameters are as follows:
   56 - This is the width in mm that we set our Cell
   6 - This is the height in mm
   'Description' - Text to display inside the Cell
   0 - This is for the border. 1 = border and 0 = no border.
   0 - This is the position for our next Cell/MultiCell. 0 will fit the next cell in to the right of this one and 1 will fit the next cell underneath.
   L - This is the alignment of our Cell. L = Left, R = Right and C = Centered.
   FALSE - This is whether or not we want our Cell to have background fill colour.

// Next we add our MultiCell.
$fpdf->MultiCell(100, 6, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse iaculis quam nec nibh fringilla euismod. Nam accumsan neque eget lorem scelerisque vestibulum.", 0, 'L', FALSE);
// These parameters are the same as the Cell function, however the value 6 is referring to the height for each line rather than in total and the Parameter for where the next Cell is to be positioned is not in the MultiCell function - Cells will automatically appear below.

This will display in your PDF document as below:

Do it with STYLE

So now we can add some plain text, let's spice things up with some style. Any styles need to come before the Cell and MultiCell functions.

// First we set the style of our cell - (We have Verdana below - but this function is also for swapping between font families)
$fpdf->SetFont('Verdana', 'B'); // Make our text bold.

// Lets set our font colour - this is in the format of R,G,B
$fpdf->SetTextColor(255, 255, 255); // Set text to the colour white.

// If we want our Cell to have a background colour or a border we use the following:
$fpdf->SetFillColor(0, 0, 0); // Set background colour to black
$fpdf->SetDrawColor(31, 152, 152); // Set the border colour to Aqua
$fpdf->SetLineWidth(1); // Set our line width of our border to 1mm
// Now we output a Cell to display the above styles.
$fpdf->Cell(30, 6, 'This is white text on a black box', 1, 0, 'L', TRUE);
// Then for example if we wanted the next cell to have orange text we would change the text colour
$fpdf->SetTextColor(242, 154, 0);
$fpdf->Cell(30, 6, 'This is orange text on a black box', 1, 0, 'L', TRUE);

The code above will create the following in your PDF document:

Styles are automatically carried across to cells going forward until the style is re-declared. So in the above example the second box with the orange text remains with the black fill colour we had set before our white text cell.

Using X and Y Axes for Navigation

So the above is fine if you are going to build your document Cell by Cell. However if you want to either find your X/Y position or move to a different location on the page you will need to use the following functions.

// Check where we are currently located on the page
$fpdf->GetX(); // Return how many mm we are from the left of the page.
$fpdf->GetY(); // Returns how many mm we are from the top of the page.
// Move to a new point on our page.
$fpdf->SetXY(50, 40); // This will move us 50mm from the left and 40mm from the top of our page. Functions SetX and SetY can be used for setting these points separately.
// Now we insert our Cell which will be positioned at the co-ordinates 50,40
$fpdf->Cell(80, 6, 'This is where we have moved our XY position to', 0, 0, 'L');


Inserting an Image

To display an image onto our PDF file using our PHP library we use the Image function.

$fpdf->Image('fpdf/image.jpg', 100, 60, 100, 80);
// The above parameters are: The image file path, The X position, The Y position, width, height. Note that the X and Y position are for where the top left hand corner sits on the page.
Make sure when inserting your image that your image is a decent size. Ideally at least the size you are inserting it as (in mm). Also if your file does have different dimensions to the size you are inserting it at, make sure the ratios are the same to avoid 'squished' looking images.

Drawing a Rectangle

I am mentioning this function as I have used this regularly for inserting page borders. To insert a rectangle/border we use the FPDF function Rect.
// So as we learnt above for styles, we will set our border's width and colour
$fpdf->SetDrawColor(234, 36, 227); // Hot Pink
$fpdf->SetLineWidth(2); // We will change the line width now to 2mm
$fpdf->Rect(5, 150, 200, 80, 'D');
// The first two parameters are setting where to begin drawing (X & Y). The second two are the width & height of our rectangle. D stands for draw - so this will display a rectangle with a border only. If this was F it would show a solid rectangle in a block fill colour (F = Fill). DF does both of these.


Displaying Page Numbers

Above we set up an attribute so we would be able to use page numbers on our pages. To display the current page number we use the function PageNo.
For example:
// First we will change the XY position to the bottom left hand corner of the page to display our page number in.
$fpdf->SetXY(190, 290);
// Now we display our page number using the Cell function.
$fpdf->Cell(30, 4, 'Page ' . $fpdf->PageNo(), 0, 1);


Lets Publish our Masterpiece

Now that we have added our content we can build our PDF with the Output function.

$fpdf->Output('Filename.pdf', 'I');
// The first parameter is what we are naming our file. The second parameter is the destination of your file.
// 'I' - This outputs the file to the browser - the file name is what it will default to if 'Save As' is selected. 'D' will force the file to be downloaded. 'F' will save the PDF file locally (To do this you need to include the file path in the file name field also).

Example and Source Code

To view an example of what the above code will create in a PDF document click here.
You can also download the source code for the above example here.

But wait... What sort of projects would I use this for?

Previous projects I have used this library for include:

1. Creating Property Flyers for Limelight's Real Estate Module, which is available as one of our modules for our in-house built CMS 'Orbit'. This extracts the information from the client's property listings displayed on their websites and displays them in a printable flyer, which can be useful for printing out to take to open homes, or for displaying on the property listings of their website for users to download.

2. Creating a Catalogue to showcase a client's monthly products. For one of limelight's clients, I built a catalogue displaying the products from their website onto a catalogue, for printing and mailing to customers. This has reduced hours spent each month tediously building the latest catalogue in a word document, to a 30 second click of a button!


In conclusion FPDF is a great tool for dynamically creating PDF files for PHP coders. My tutorial is just the basic functions you can use with the FPDF library. For a list of all the functions, you can read the manual listed on the official FPDF website http://www.fpdf.org/

Please feel free to get in touch with us at Limelight Online if you have any questions.

Add a comment38 Comments

Reply Anzum Huda (Author) | August 22nd, 2013 at 6:33pm
Thank You.. for this beautiful and easy tutorial...It covers all in details...
Reply Shay Porteous (Author) | January 27th, 2014 at 3:14pm
No worries :) Glad to help
Reply Rajkamal (Author) | December 21st, 2013 at 2:11am
I need background water mark image in center my pdf. Please help me.
Reply Shay Porteous (Author) | January 27th, 2014 at 3:16pm
Hi, You should be able to enter it just as a normal image first then you can set your X-Y position to write over top of your image. Let me know if you have any further questions :D
Reply Mack (Author) | January 29th, 2014 at 3:42pm
How can i put headers and footer?
Reply Shay Porteous (Author) | March 12th, 2014 at 11:42am
Hi Mack,

If you go to the http://www.fpdf.org/ website you will see there is actually a function for setting a header and a footer (this is under the Manual part of the site).

Reply Sven Tantau (Author) | January 31st, 2014 at 3:56am
Hi Shay,

I used a similar approach to generate PDFs in my software.

My pain point with this was that I had to support my clients when they needed layout changes or to do the initial setup.

So after running some tests with latex-templates, I created Template2PDF (http://template2pdf.com/) which is an API to generate PDFs out of OpenOffice or LibreOffice documents.

I would be very happy about any kind of feedback you can give me on that.

Best regards,
Reply Dillip (Author) | March 12th, 2014 at 12:11am
How can I add page border line in PDF. I use the following code but it doesn't work.
Reply Shay Porteous (Author) | March 12th, 2014 at 11:40am
Hi Dillip,
Thanks for your comment. For creating borders you can use the Rect() function for creating rectangles. Rect(position x, position y, rectangle width, rectangle height). The colour of this can be set before calling this function with SetDrawColor(r,g,b).

Hope that helps

Reply Radheshyam Kori (Author) | March 27th, 2014 at 7:27pm
Thanks Shay ,
Thanks a lot. I am new to PHP and was searching onine for creating pdf by fetching records from database and display it. I went through http://www.fpdf.org as well but the way explained in your Tutorial made me to understand better for setting Text fonts, color, page borders, giving page nos, which is very helpful in creating dynamic pdf file by fetching records from a database and displaying it
Reply Shay Porteous (Author) | March 28th, 2014 at 8:06am
Hi Radheshyam,

That's what I like to hear! Glad I could help :)

Reply Loki (Author) | April 2nd, 2014 at 12:06am
Hi,i am new in php and i want to know how to create a pdf in icard/business card size,by fetching the data from database along with the image..
Reply Shay Porteous (Author) | April 24th, 2014 at 8:30am
Hi Loki,

You can create the PDF using my tutorial but instead of hard coding images and text in the cells, you can do an SQL statement to pull them out of your database :)

Reply Josh Salise (Author) | April 24th, 2014 at 2:15am
hello love :) i was hoping you can help with my problem. i was kinda want the word description inside the cell to be bold w/o affecting inside the multicell. thank you :))
Reply Shay Porteous (Author) | April 24th, 2014 at 8:28am
Hi Josh,

Sorry you will need to split this into two Cells - I don't believe there is a way to just add into your cell like you can with HTML.

Reply Frans (Author) | May 13th, 2014 at 12:46pm
Hi Shay,

I have listing of ID in datagrid. Now i can create pdf just as user checked the checkbox which ID that they want to print.
My problem is, it's only generate one pdf file, that contain many ID they checked. User need to create many pdf file as many as they checked (so if they checked 3 ID, system generates 3 pdf files).

Can you help me, Shay?

Thanks and regards,
Reply Shay Porteous (Author) | November 7th, 2014 at 8:25am
Hi Frans,

Not sure if i've quite understood but you might want to loop through and save them as three individual files using the function below?

string Output([string name, string dest])
Reply Darren Wetherilt (Author) | May 14th, 2014 at 10:12pm
I'm going round in circles here. I want to create a document that has conditional pages and sections. The document needs to have an active contents page (or pages). The final structure being [Cover] - [Blank] - [Contents page(s)] - [Conditional Blank] - [Section1] - [Conditional Blank] - [Section2] - [Conditional Blank] - [Section n] - [Conditional Blank]

The blanks should only fire to force each new section to start on an odd page number (for duplex printing).

I was thinking of creating all the sections as individual PDF objects (with the blanks at the end if required) then building the contents page(s) before compiling them altogether into one document but not really sure how I would get that done. Any ideas????
Reply Liliana (Author) | June 4th, 2014 at 4:57am
Hi Shay,
very helpful and good explained. Thanks. I would like to ask you if you know the problem that the pdf file will be not refreshed after creating it with different data. I run a program which generates a pdf according with some parameters, it select data from database a put it into the pdf, but if i run it again, let's say for another product, it seems not to create a new one. I just tried to changed the pdf tittle, then I changed my code with another title and run again the php script. It shows me the old title. It's as the pdf remain in memory and is not created again.
I would be greatly appreciated if you have a tip for me
Reply dass (Author) | June 6th, 2014 at 4:00pm
i want support multiple language support pdf creator. any possible
Reply Mario (Author) | June 22nd, 2014 at 4:28am
Thanks, it is a very nice explanation.
Reply shashikant (Author) | June 26th, 2014 at 6:30pm
wow such a great article its help me a lot.
Reply Pushpendra (Author) | July 19th, 2014 at 12:51am
I am getting problem to adjust image cell and text cell they are not in order. how can i order this cell. my code is here.


Reply Shay Porteous (Author) | November 7th, 2014 at 8:20am

Instead of setting X & Y as Null - try using GetX() and GetY() - that should get where you are and pop your image in the right place :)
Reply Divy Singh Rathore (Author) | August 11th, 2014 at 3:13am
How to force a file to download without opening pdf in browser.
Reply Shay Porteous (Author) | November 7th, 2014 at 8:27am
string Output([string name, string dest])
Reply suneel (Author) | September 18th, 2014 at 8:57pm
hi i am thankfull really nice
Reply vikrant sharma (Author) | September 23rd, 2014 at 4:47pm
how to draw vertical lines???
i want to add box between two lines.
please help
Reply Shay Porteous (Author) | November 7th, 2014 at 8:21am
To draw a box you can use the function below :)

Rect(float x, float y, float w, float h [, string style])
Reply Online Marketing Management (Author) | October 13th, 2014 at 11:00pm
What's Happening i am new to this, I stumbled upon this I have found
It absolutely helpful and it has helped me out loads.
I hope to contribute & aid other users like its aided me.
Good job.
Reply plumbers10133.mozello.com (Author) | November 7th, 2014 at 4:29am
Hi there it's me, I am also visiting this site on a regular
basis, this site is genuinely nice and the users are actually sharing nice thoughts.
Reply Lee (Author) | August 12th, 2015 at 4:08am
Hi Shay, great article - I'm a beginner trying to learn all the different functions and techniques. I was wondering, if I already have a page, how can I add a new page before the existing page? I created the addpage function and page break, but nothing is appearing. What am I doing wrong?
Reply Nigel Wells | August 12th, 2015 at 8:33am
Hi Lee
You'll want to make use of the function "addPage()"
The thing with creating PDF documents using FPDF is it is built in the direct order of your code so you can't prepend any of your code or pages. In order to add a page prior to an existing page you'll need to do just that - add your new page before the code that creates the existing page.
Hope this helps.
Reply Grace (Author) | October 26th, 2015 at 11:22pm
This is a wonderful tutorial.

Please can you point me to an fpdf tutorial that shows images from blobs stored in the database? I've looked every where and tried so many and none work.

Thank you
Reply Nigel Wells | October 27th, 2015 at 9:54am
Hi Grace, the FPDF class comes packaged with the ability to parse PNG, JPEG, and GIF files. It assumes you have a file physically saved on the web server to use. In saying that, from looking at the $FPDF->_parsejpg() function all that is happening is it returns an array with some set values that describe the image as well as the data to construct it. The $FPDF->Image() function then creates a placeholder for the image but it isn't until the PDF is constructed and _putimages() is run that the image is embedded.
I see two options here: 1) Physically save your blob images as a file, create the PDF, delete (unlink) your blob images. 2) Extend the FPDF class and create your own ImageBlob() function to handle the data being passed rather than reading it from a physical file.
Hope this helps point you in the right direction!
Reply satya (Author) | January 22nd, 2016 at 10:55pm
Hi i am new to PHP,
Your explanation is much better than the official website tutorials.

I have small doubt , what if i have to link a text such as "google.com" and when clicking,it should direct me to google.com ,
my main doubt is how to direct it to browser instead of linking it to internal targets.

Thank you.
Reply Nigel Wells | January 25th, 2016 at 3:13pm
I believe identified links are automatically converted into hyperlinks for you. Alternatively you could extend your class similar to this website http://www.fpdf.org/en/script/script42.php and then make use of simple HTML to create a link. Essentially you're just making use of the PutLink() function which you could use directly if you wanted.
Reply satya (Author) | January 25th, 2016 at 8:08pm
Thanks for the response,tried your suggestion just now. It worked.
Thank you and keep the good work goin on.

Leave a comment

Fields marked * are required