« RSS Parsing using PearPHP and The Twitter API »

Create PDF file with PHP Posted in PHP Tutorials | 25 Comments
PDFs have become widespread enough among businesses and institutions to make automatically and dynamically producing them in large quantity is a valuable skill to learn. Portable Document Files from Adobe are easily produced in PHP, making it an even better glue language than before. Since anyone can install PHP, they can use the simple PHP 5 class of PDFlib that's provided to make a as many PDFs in whatever format you need.

The irony is, of course, PDFlib is now commercial and offers a PDFlib Lite. Either way, the PDFlib library has an unwieldy learning curve, and instead, I recommend FPDF for your general PDF usages. This is a freeware PDF library written completely in PHP, so no PECL or PEAR installation is required, which does slow it down. So, a large business shouldn't use this to process hundreds of PDFs, but for smaller jobs it works.

Making a basic PDF document on the fly

I'll show you how to make a basic PDF document with text blocks of different alignments, as well as double-spacing, headers and footers and displaying an image.

Let's jump immediately into an example showing all of this:

<?php
require('classes/fpdf/fpdf.php');
class PDF extends FPDF {

function Header() {
$this->SetFont('Times','',12);
$this->SetY(0.25);
$this->Cell(0, .25, "John Doe ".$this->PageNo(), 'T', 2, "R");
//reset Y
$this->SetY(1);
}

function Footer() {
//This is the footer; it's repeated on each page.
//enter filename: phpjabber logo, x position: (page width/2)-half the picture size,
//y position: rough estimate, width, height, filetype, link: click it!
$this->Image("logo.jpg", (8.5/2)-1.5, 9.8, 3, 1, "JPG", "http://www.phpjabbers.com");
}

}

//class instantiation
$pdf=new PDF("P","in","Letter");

$pdf->SetMargins(1,1,1);

$pdf->AddPage();
$pdf->SetFont('Times','',12);

$lipsum1="Lorem ipsum dolor sit amet, nam aliquam dolore est, est in eget.";

$lipsum2="Nibh lectus, pede fusce ullamcorper vel porttitor.";

$lipsum3 ="Duis maecenas et curabitur, felis dolor.";

$pdf->SetFillColor(240, 100, 100);
$pdf->SetFont('Times','BU',12);

//Cell(float w[,float h[,string txt[,mixed border[,
//int ln[,string align[,boolean fill[,mixed link]]]]]]])
$pdf->Cell(0, .25, "lipsum", 1, 2, "C", 1);

$pdf->SetFont('Times','',12);
//MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
$pdf->MultiCell(0, 0.5, $lipsum1, 'LR', "L");
$pdf->MultiCell(0, 0.25, $lipsum2, 1, "R");
$pdf->MultiCell(0, 0.15, $lipsum3, 'B', "J");

$pdf->AddPage();
$pdf->Write(0.5, $lipsum1.$lipsum2.$lipsum3);

$pdf->Output();
?>


I create a PDF in Portrait mode with a Letter size and measured in inches. Then, I set the margins to 1 inch, add our first page, and then set the Font to Times, Size 12. Then, my 3 dummy texts, and after that I set the fill color that will be the space behind my title's text with a bold/underlined modifier. After that, I print the title, then reset the font and specify some different types of MultiCells. The page is made up of cells on an x,y plane in FPDF, which makes it pretty convenient to work with for basic PDF editing.

The headers and footers are functions automatically called in the parent class, but they do nothing by default. That means we have to redefine them to our needs. In this case, a name and page number as the header and a logo with a link as the footer. These are repeated on each page.

Note that in order to place the text in the proper location, I had to use the SetX and SetY functions. Don't forget to reset them to their normal flow when you're done in the header or footer, though!

Cells are individual units on the page. It is convenient to define a line with a single cell, but at the same time this can be achieved much more quickly by use of the MultiCell function which will automatically create a new cell as text is passed through. Write is just streamed text.

One thing to absolutely keep in mind is that you can't output any text to the browser when trying to send this PDF to the browser, if you're making it on the fly. If you're making it for storage or later use, then there's no problem outputting text to the user as well. This is accomplished by setting the parameters to Output appropriately.

The spacing is done with the line height. You have to do some math to figure out what you want. The line height is the entire height of the line, which means the lines are up against each other. That means whatever you set for the line height is spacing between the letters, as well!

With these skills in mind, you should be able to do whatever you want to a PDF. For even more functionality, there is a Scripts section, but of course there is always the PDFlib library which provides all kinds of specialization. FPDF is a highly documented library though, and it's really simple to use. Good luck!

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your experience with millions of other webmasters visiting our website. Contact us for more information how to become a contributor.

25 Replies to "Create PDF file with PHP"

deepa November 21, 2013 at 9:15 am | Reply

+10

where cani find classes/fpdf/fpdf.php file
M. Ghoshal February 5, 2014 at 5:04 am

+6

You can give a file search for fpdf.php and you will be able to find the location. E.g., in my system it is in the folder: C:\xampp\php\pear\fpdf\fpdf.php. Hope this helps.
Hillybilly September 17, 2013 at 11:08 am | Reply

+3

Huge. Tremendous. Thanks
David June 20, 2013 at 4:47 am | Reply

+9

I am using a database on my website and I was curious if there is a good way to call information from the database to put in the PDF?

If I am calling it on a general php page and the user is logged in, I can just add; <code><?php
if($form->value("fname") == ""){
echo $session->userinfo['fname'];
}else{
echo $form->value("fname");
}
?></code>

With this script (using the first tutorial), it just wants simple text in between ' ' (it shows 'Hello World' in the tutorial). If I put that code there, it completely destroys the structure.
komal April 11, 2013 at 12:39 pm | Reply

+11

interesting.. going to use it for my website.
fervendra April 5, 2013 at 2:50 pm | Reply

+4

great code...
CHANDAN SINGH NEGI April 1, 2013 at 3:13 pm | Reply

+2

VERY NICE, GOOD TUTORIAL FOR BASIC KNOWLEDGE..
syed April 1, 2013 at 7:38 am | Reply

+2

interesting.. going to use it for my website.
tutgeeks March 18, 2013 at 3:11 am | Reply

0

nice tutorial..it helps me a lot...visit me at my website... www.tutgeeks.com
Sonia January 29, 2013 at 7:12 am | Reply

+4

Please a quick doubt.. where do i write the php code file ?? in which location .. I am using Drupal ..
Imtiaz Hussain May 10, 2014 at 11:49 am

0

you've to keep your code save in htdocs with the xtentin of php. thankyou.
Pradeep Rai K December 5, 2012 at 1:55 pm | Reply

+6

Nice Job...Thank you lot.


Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~