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.

 

Our crack team of developers specialises in crafting custom website integrations. We’re the bridge between your unique needs and the power of external applications. No matter the platform, we can seamlessly connect your website to the tools that supercharge your business. Reach out for a chat and we’ll let you know if we can provide the solution you need. 

 

Head here to our contact page to get in touch.

Related

Design & Development
And Now, How to Build the Perfect eCommerce Product Page
Design & Development
How to Build the Perfect eCommerce Product Category Page
Design & Development
How to setup a 301 Permanent Redirect
Design & Development
And Now, How to Build the Perfect eCommerce Product Page
Design & Development
How to Build the Perfect eCommerce Product Category Page
Design & Development
How to setup a 301 Permanent Redirect

Our thoughts

Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate • Let's collaborate

Like what you see?
Get in touch

"*" indicates required fields

Your personal information will only be used to service your enquiry. We will only contact you with relevant information. For further information view our full Privacy Policy.
This field is for validation purposes and should be left unchanged.

CONTACT

Hi, let's see how
we can help

"*" indicates required fields

Your personal information will only be used to service your enquiry. We will only contact you with relevant information. For further information view our full Privacy Policy.
This field is for validation purposes and should be left unchanged.

MENU

Looking for Apex Digital?

You’re in the right place, we’re now Limelight, the same people and same great work.