The FPDF Library

csixty4 6,460 views 16 slides Dec 27, 2009
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

Mike Creuzer's presentation from the May, 2009 meeting of the Suburban Chicago PHP & Web Development Meetup


Slide Content

FPDF
Creating PDF files with PHP
http://www.fpdf.org/
By Mike Creuzer
mike.creuzer.com
For: The West Suburban Chicago PHP Meetup Group
http://suburbanchicagophp.org/

Why Create PDF files?
•Because your client wants one
•Because you need pixel-perfect positioning on printed pages
•Because you want to have a 'saveable' page
•Because you want an 'immutable' page
•Because some things are done easier in PDFs then HTML
•Because you may want a password protected document
•Because you want to create the impression of a document
•Because, Because, Because... Because of the wonderful
things it does...

Why FPDF?
FPDF is an existing library, used by many people.
Pros:
•Written by somebody else - no re-inventing the wheel
•Tested, debugged, and hopefully working code
•Flexible, extensible, many different modules
•Many examples of different things you can do with it
•The price is right! Free!
Cons:
•A bit of a learning curve to get started
•Infrequently updated (Could just be 'done' at this point)

What does FPDF say about itself?
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to
say without using the PDFlib library. F from FPDF stands for Free: you may use it
for any kind of usage and modify it to suit your needs.
FPDF has other advantages: high level functions. Here is a list of its main
features:
•Choice of measure unit, page format and margins
•Page header and footer management
•Automatic page break
•Automatic line break and text justification
•Image support (JPEG, PNG and GIF)
•Colors
•Links
•TrueType, Type1 and encoding support
•Page compression
FPDF requires no extension (except zlib to activate compression and GD for GIF
support) and works with PHP4 and PHP5.
Source: http://www.fpdf.org/

A brief example from fpdf.org:
<?php
  require('fpdf.php');
  $pdf = new FPDF();
  $pdf->AddPage();
  
  $pdf->SetFont('Arial', 'B', 16);
  $pdf->Cell(40, 10, 'Hello World!');
  
  $pdf->Output();
?>
Include the class library
Create a new class object
Add a page to the PDF document
Set the font
Create a 'cell' and put some text into it
Output the PDF file

A few tips
The $pdf->Output(); call issues headers so the mime type is
right so the browser can view the file as a .pdf. Outputting
anything directly to the browser before the output call causes a
HTML header to be sent at that point, breaking the PDF file.
Any output after the call gets interpreted as part of the file,
corrupting the PDF file format. Watch those empty lines after
the ?>
To add functionality, you extend the class. There are many
examples of class extensions in the 'scripts' page.

What I have used FPDF for in the past
•Auto Generated Printable Course CalendarA
Created a 'Calendar' format list of classes available to students.Many
people work of that format better than a list.
•Dynamic pre-populated Fax Cover sheet
From a contact detail screen, create a pre-filled fax cover sheetExtra
space on the cover sheet is upcoming calendar events
•Automatic Name BadgesA
Create Avery formated name badges
Include event logo watermarked on the badgeAutoscale long names to
fit width of the badge

Dynamic Name Badge PDF Creation
8 name badges ready to print!
Includes watermarked event logo!

Name Badge Process
I chose to use fpdf to create name badges as a PDF file is
formatted for a printed page as opposed to a computer screen.
Steps to create a namebadge in a PDF file:
–Define the size of a badge on the page & spacing between
badges
–Create a .PDF file ready for inserting the names
–Add the watermarked event image
–Scale and add the person's name
–Scale and add the person's company
–Calculate where the next badge should be placed on the
page
–Output the completed PDF file

Working code example: Setting Params
require("{$_SERVER['DOCUMENT_ROOT']}/lib/fpdf/fpdf.php");
$result = getanevent($location, $date); // Get list of names/companies
$duplicates = $duplcatesdata = $staffdata = array();
$name = "{$location}_{$date}__(" . date("Y-m-d", time()) . ").csv";
// Avery 5895
$topMargin = 5/8;
$leftMargin = 11/16;
$bottomMargin = 1/2;
$height = 7/3;
$width = 27/8;
$gutter = 3/8;
$gap = 11/64;
// Create the PDF class object
$pdf=new FPDF('P', 'in', 'Letter');
$pdf->SetTopMargin($topMargin);
$pdf->SetLeftMargin($leftMargin);
$pdf->SetAutoPageBreak(TRUE, $bottomMargin - .2);
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);

Detect and skip duplicates
$rowcounter = 1; // (actually columns) so we know how many labels we have done
foreach($result as $record) // loop through the names
{
// Look for duplicate names
if( in_array("{$record[1]} {$record[2]}", $duplicates) )
{
//$duplicatesdata[] = $record;
}elseif( strtolower(substr($record[7], -20)) == 'hexagonmetrology.com')
{ // Looking for staff and skipping
//$staffdata[] = $record;
// We could also print a staff badge here
}else{

Scaling the names/company names
/ / Pri nt t he wat ermark
$pdf->I mage(" { $_SERVER[ ' DOCUMENT_ROOT' ] } / LOGO. j pg",  $pdf->Get X( )  + . 5,  $pdf-
>Get Y( )  + . 55,  $wi dt h -1 ) ;
// Create and capitalize the name from firstname & lastname
$content = ucwords($record[1]) . " " . ucwords($record[2]) ;
$textsize = 28; // default font size
$pdf->SetFont('Arial','B',$textsize);
while( $pdf->GetStringWidth($content) > $width - .6)
{ // loop while the name is too big for the badge
$textsize--;
$pdf->SetFont('Arial','B',$textsize);
}
// Add the name to the badge
$pdf->Cell($width, $height/2, $content, '', '2', 'C');

/ /  Capi t al i ze t he company name
$content = ucwords($record[3]);
$textsize = 18;// smaller default font size for the company
$pdf->SetFont('Arial','B',$textsize);
while( $pdf->GetStringWidth($content) > $width - .6)
{// loop while the company name is too big for the badge
$textsize--;
$pdf->SetFont('Arial','B',$textsize);
}
                     $pdf->Cel l($wi dt h,  $hei ght/2,  $cont ent,  ' ',  ' ',  ' C') ;

Setting up for the next badge
// Save this name for duplicate detection
$duplicates[] = "{$record[1]} {$record[2]}";
if($rowcounter % 2 == 0) // Even columns, not rows
{
$pdf->Ln( ($height/2) + $gap); // start again at a new line
}else // odd (1st) columns
{
$pdf->SetXY($pdf->GetX() + $gutter, $pdf->GetY() - ($height/2) );
//$pdf->SetY($pdf->GetY() - ((7/3)/2));
}
if($rowcounter % 8 == 0) // end of page
{
$pdf->AddPage();
}
$rowcounter++; // increment the badge counter
}
}
// Output the pdf file
$pdf->Output(); // could pass in $name if we wanted to save as a file
die(); // Hack to make the file download work in Joomla

FPDF class functions used
FPDF - constructor
SetTopMargin - set top margin
SetLeftMargin - set left margin
SetAutoPageBreak - set the automatic page breaking mode
AddPage - add a new page
SetFont - set font face, style, size
Image - output an image
GetStringWidth - compute string length
Cell - print a cell
Ln - line break
SetXY - set current x and y positions
Output - save or send the document

Other examples of what FPDF can do:
Barcodes
Calendars
Charts
Trees
Use existing PDFs as templates
Labels
Javascript Support in a PDF
HTML formatting
CMYK & Pantone color support

Any Questions?
Thank you for your time.