BLOG
Create a Dynamic PDF with PHP (Tutorial)
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.
<?php
require_once('fpdf/fpdf.php');
?>
Set up some default values for your PDF Document:
<?php
// 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.
$fpdf->AliasNbPages();
?>
Link to the font files to access the fonts you want to use:
<?php
// 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.
<?php
$fpdf->AddPage();
?>
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.
<?php
// Set font size
$fpdf->SetFontSize(10);
// 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.
<?php
// 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.
<?php
// 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');
?>
Example:
Inserting an Image
To display an image onto our PDF file using our PHP library we use the Image function.
<?php
$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.
<?php
// 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.
?>
Example:
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:
<?php
// 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);
?>
Example:
Lets Publish our Masterpiece
Now that we have added our content we can build our PDF with the Output function.
<?php
$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!
Conclusion
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
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).
Thanks,
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,
Sven
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
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
That's what I like to hear! Glad I could help :)
Thanks,
Shay
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 :)
Thanks
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.
Thanks,
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,
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])
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????
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
Thanks,
Liliana
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.
$this->SetFillColor(255,255,255);
$this->SetDrawColor(128,0,0);
$w=array(20,10,130,5);
$this->Image($path,$x=null,$y=null,$w=20,$h=20);
$this->Cell(10,20,$eachResult["lotnum"],1,0,'C');
$this->Cell(130,20,$eachResult["short_description"],1,0,'C');
$this->Cell(5,20,$eachResult["quantity"],1,0,'C');
$this->Ln(5);
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 :)
i want to add box between two lines.
please help
Rect(float x, float y, float w, float h [, string style])
It absolutely helpful and it has helped me out loads.
I hope to contribute & aid other users like its aided me.
Good job.
basis, this site is genuinely nice and the users are actually sharing nice thoughts.
You'll want to make use of the function "addPage()"
$fpdf->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.
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
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!
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.
Regards
Nigel
Thank you and keep the good work goin on.