...Beauty, cleaning, DIY tips and more - free to join!
   Login   Contact us   Site map   Puzzle Club   Ask a question    Newsletter

Create PDFs dynamically using PHP and FPDF...

At some stage most of us need to output PDF documents for clients, often dynamically created on the back of input from the user.

One way to do this is to use the simple to understand put powerful and very popular PHP language, and to create PDFs use the class called FPDF.

This is completely free, and you can download it from www.fpdf.org

The great thing is that you don't need to understand anything about the internal workings and machinations of the class - all you need to learn is how to access and call its functions, or methods.

There is a very clear set of tutorials to this end; but here is the basis of how to use FPDF to create a very simple PDF document.

The first thing that you need to do at the top of any document that will create a PDF is to include the class. To do this simply use

require('fpdf.php');

This will now include the class and the page will die if it cannot be found (note therefore it is better to use require than include here).

Then you need to create a new PDF document. Do this with:

$pdf = new FPDF();

Then you add a page to it:

$pdf->AddPage();

You then choose your fonts and any styling you want and font size, like so:

$pdf->SetFont('Arial', 'B', 12);

This gives you a bold arial, size 12 font as I'm sure you can guess.

The general method to write textual content is to create a cell, and then within that include the text. The most important method to get used to is the cell, as there are many optional parameters. So you should take the time to read the relevant page from the manual - linked to at the FPDF site mentioned above.

To add a cell that is 40 wide by ten high and include the classic Hello World text we do this:

$pdf->Cell(40,10,'Hello World!');

Finally, when we are ready to output this simple PDF, we do this:

$pdf->Output();

Remember that you must not try to print anything to the browser anywhere or the creation of the PDF will fail as standard headers will be sent out automatically.

Also if you want to save the PDF somewhere rather than dump to the screen, then simply pass a filename, e.g.
$filename = "helloworld.pdf";

$pdf->Output($filename);

Then when the page is called you will simply get the blank white screen in your browser that says 'Done' and the file will be saved at the specified location and filename.
PDF Creation With PHP
Author: Stephen

About the Author:
More About the Author >>> | My other pages >>>

Page Views: 1512 | Page Ranking: 152
Popular Tags:
PDF creation, create PDF, PHP and PDF, FPDF class

Last Updated: Sep 29th 2006

Ask Stephen a Question >>>

Write your own expert page!
Category: Computers and Internet [More Categories]

Article Comments / Questions

No comments have been added to this question.
Comment on this Article