The FPDF Library

14,454 views

Published on

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

Published in: Technology
1 Comment
1 Like
Statistics
Notes
No Downloads
Views
Total views
14,454
On SlideShare
0
From Embeds
0
Number of Embeds
109
Actions
Shares
0
Downloads
110
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide

The FPDF Library

  1. 1. 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/
  2. 2. Why Create PDF files? <ul><ul><li>Because your client wants one </li></ul></ul><ul><ul><li>Because you need pixel-perfect positioning on printed pages </li></ul></ul><ul><ul><li>Because you want to have a 'saveable' page </li></ul></ul><ul><ul><li>Because you want an 'immutable' page </li></ul></ul><ul><ul><li>Because some things are done easier in PDFs then HTML </li></ul></ul><ul><ul><li>Because you may want a password protected document </li></ul></ul><ul><ul><li>Because you want to create the impression of a document </li></ul></ul><ul><ul><li>Because, Because, Because... Because of the wonderful things it does... </li></ul></ul>
  3. 3. Why FPDF? <ul><li>FPDF is an existing library, used by many people. </li></ul><ul><li>Pros: </li></ul><ul><ul><li>Written by somebody else - no re-inventing the wheel </li></ul></ul><ul><ul><li>Tested, debugged, and hopefully working code </li></ul></ul><ul><ul><li>Flexible, extensible, many different modules </li></ul></ul><ul><ul><li>Many examples of different things you can do with it </li></ul></ul><ul><ul><li>The price is right! Free! </li></ul></ul><ul><li>Cons: </li></ul><ul><ul><li>A bit of a learning curve to get started </li></ul></ul><ul><ul><li>Infrequently updated (Could just be 'done' at this point) </li></ul></ul>
  4. 4. What does FPDF say about itself? <ul><li>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. </li></ul><ul><li>FPDF has other advantages: high level functions. Here is a list of its main features: </li></ul><ul><ul><li>Choice of measure unit, page format and margins </li></ul></ul><ul><ul><li>Page header and footer management </li></ul></ul><ul><ul><li>Automatic page break </li></ul></ul><ul><ul><li>Automatic line break and text justification </li></ul></ul><ul><ul><li>Image support (JPEG, PNG and GIF) </li></ul></ul><ul><ul><li>Colors </li></ul></ul><ul><ul><li>Links </li></ul></ul><ul><ul><li>TrueType, Type1 and encoding support </li></ul></ul><ul><ul><li>Page compression </li></ul></ul><ul><li>FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5. </li></ul>Source:  http://www.fpdf.org/  
  5. 5. A brief example from fpdf.org: <ul><li><?php </li></ul><ul><li>   require( 'fpdf.php' ); </li></ul><ul><li>   $pdf  = new  FPDF (); </li></ul><ul><li>   $pdf -> AddPage ();    </li></ul><ul><li>   $pdf -> SetFont ( 'Arial' ,  'B' ,  16 ); </li></ul><ul><li>   $pdf -> Cell ( 40 ,  10 ,  'Hello World!' );    </li></ul><ul><li>   $pdf -> Output (); </li></ul><ul><li>?> </li></ul><ul><li>Include the class library </li></ul><ul><li>Create a new class object </li></ul><ul><li>Add a page to the PDF document </li></ul><ul><li>Set the font </li></ul><ul><li>Create a 'cell' and put some text into it </li></ul><ul><li>Output the PDF file </li></ul>
  6. 6. A few tips <ul><li>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.  </li></ul><ul><li>Any output after the call gets interpreted as part of the file, corrupting the PDF file format. Watch those empty lines after the ?> </li></ul><ul><li>To add functionality, you extend the class. There are many examples of class extensions in the 'scripts' page.  </li></ul>
  7. 7. What I have used FPDF for in the past <ul><ul><li>Auto Generated Printable Course Calendar </li></ul></ul><ul><li> Created a 'Calendar' format list of classes available to students.Many people work of that format better than a list. </li></ul><ul><ul><li>Dynamic pre-populated Fax Cover sheet </li></ul></ul><ul><li>From a contact detail screen, create a pre-filled fax cover sheetExtra space on the cover sheet is upcoming calendar events </li></ul><ul><ul><li>Automatic Name Badges </li></ul></ul><ul><li> Create Avery formated name badges Include event logo watermarked on the badgeAutoscale long names to fit width of the badge </li></ul>
  8. 8. Dynamic Name Badge PDF Creation <ul><li>8 name badges ready to print! </li></ul><ul><li>Includes watermarked event logo! </li></ul>
  9. 9. Name Badge Process <ul><li>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. </li></ul><ul><li>Steps to create a namebadge in a PDF file: </li></ul><ul><ul><li>Define the size of a badge on the page & spacing between badges </li></ul></ul><ul><ul><li>Create a .PDF file ready for inserting the names </li></ul></ul><ul><ul><li>Add the watermarked event image </li></ul></ul><ul><ul><li>Scale and add the person's name </li></ul></ul><ul><ul><li>Scale and add the person's company </li></ul></ul><ul><ul><li>Calculate where the next badge should be placed on the page </li></ul></ul><ul><ul><li>Output the completed PDF file </li></ul></ul>
  10. 10. Working code example: Setting Params <ul><li>             require( &quot;{$_SERVER['DOCUMENT_ROOT']}/lib/fpdf/fpdf.php&quot; );              $result  =  getanevent ( $location ,  $date );  // Get list of names/companies </li></ul><ul><li>             $duplicates  =  $duplcatesdata  =  $staffdata  = array();                      $name  =  &quot;{$location}_{$date}__(&quot;  .  date ( &quot;Y-m-d&quot; ,  time ()) .  &quot;).csv&quot; ;              // Avery 5895              $topMargin  =  5 / 8 ;              $leftMargin  =  11 / 16 ;              $bottomMargin  =  1 / 2 ;              $height  =  7 / 3 ;              $width  =  27 / 8 ;              $gutter  =  3 / 8 ;              $gap  =  11 / 64 ; </li></ul><ul><li>                             // 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 ); </li></ul>
  11. 11. Detect and skip duplicates <ul><li>                             $rowcounter  =  1 ;  // (actually columns) so we know how many labels we have done </li></ul><ul><li>             foreach( $result  as  $record )  // loop through the names             { </li></ul><ul><li>                                     // Look for duplicate names                 if(  in_array ( &quot;{$record[1]} {$record[2]}&quot; ,  $duplicates ) )                 {                      //$duplicatesdata[] = $record;                  }elseif(  strtolower ( substr ( $record [ 7 ], - 20 )) ==  'hexagonmetrology.com' )                 {  // Looking for staff and skipping                      //$staffdata[] = $record; </li></ul><ul><li>                                              // We could also print a staff badge here                  }else{ </li></ul>
  12. 12. Scaling the names/company names <ul><li>                                              // Print the watermark </li></ul><ul><li>                                              $pdf -> Image ( &quot;{$_SERVER['DOCUMENT_ROOT']}/LOGO.jpg&quot; ,  $pdf -> GetX () +  .5 ,  $pdf -> GetY () +  .55 ,  $width  - 1  ); </li></ul><ul><li>                                               // Create and capitalize the name from firstname & lastname                      $content  =  ucwords ( $record [ 1 ]) .  &quot; &quot;  .  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 );                                         } </li></ul><ul><li>                                               // Add the name to the badge                      $pdf -> Cell ( $width ,  $height / 2 ,  $content ,  '' ,  '2' ,  'C' );   </li></ul><ul><li>                                               // Capitalize the company name </li></ul><ul><li>                     $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 );                                         } </li></ul><ul><li>                     $pdf -> Cell ( $width ,  $height / 2 ,  $content ,  '' ,  '' ,  'C' ); </li></ul>
  13. 13. Setting up for the next badge <ul><li>                     // Save this name for duplicate detection </li></ul><ul><li>                                              $duplicates [] =  &quot;{$record[1]} {$record[2]}&quot; ;                     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 </li></ul>
  14. 14. FPDF class functions used <ul><li>FPDF - constructor </li></ul><ul><li>SetTopMargin - set top margin </li></ul><ul><li>SetLeftMargin - set left margin </li></ul><ul><li>SetAutoPageBreak - set the automatic page breaking mode </li></ul><ul><li>AddPage - add a new page </li></ul><ul><li>SetFont - set font face, style, size </li></ul><ul><li>Image - output an image </li></ul><ul><li>GetStringWidth - compute string length </li></ul><ul><li>Cell - print a cell </li></ul><ul><li>Ln - line break </li></ul><ul><li>SetXY - set current x and y positions </li></ul><ul><li>Output - save or send the document </li></ul>
  15. 15. Other examples of what FPDF can do: <ul><li>Barcodes </li></ul><ul><li>Calendars </li></ul><ul><li>Charts </li></ul><ul><li>Trees </li></ul><ul><li>Use existing PDFs as templates </li></ul><ul><li>Labels </li></ul><ul><li>Javascript Support in a PDF </li></ul><ul><li>HTML formatting </li></ul><ul><li>CMYK & Pantone color support </li></ul>
  16. 16. Any Questions? Thank you for your time.

×