Sunday 2 December 2012

fpdf tutorials with examples


FPDF is free and uses pure PHP code. Full form of FPDF is free pdf. easily available and uses PDFlib to generate pdf files.

If you are using XAMPP with latest version you will easily find it inside xampp/php/pear/ folder. Or you can download : download fpdf

With FPDF you have: 

  • 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
Before starting you can see fpdf function manual here : http://mukundtopiwala.blogspot.in/2012/12/fpdf-manual-and-cheatsheet_2.html


Simple FPDF example

<?php
// depends on where you have placed fpdf.php
// if fpdf.php is outside fpdf directory change it to fpdf.php
require('fpdf/fpdf.php');

$pdf = new FPDF();  // $pdf = new FPDF('P','mm','A4');Default val
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Mukund Topiwala');
$pdf->Output();
// default output set to I means to browser.
?>


Example with footer, header


<?php
require('fpdf/fpdf.php');

class PDF extends FPDF
{
// Page header
function Header()
{
    // Logo
    $this->Image('logo.jpg',10,10,30);
    // Arial bold 15
    $this->SetFont('Arial','B',15);
    // Title
    $this->Cell(0,12,'Mukund Topiwala',1,0,'C');
    // Line break
    $this->Ln(20);
}

// Page footer
function Footer()
{
    // Position at 1.5 cm from bottom
    $this->SetY(-15);
    // Arial italic 8
    $this->SetFont('Arial','I',8);
    // Page number
    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'R');
}
}
// Instanciation of inherited class
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
for($i=1;$i<=5;$i++)
    $pdf->Cell(0,10,'Printing line number '.$i,0,1);
$pdf->Output();
?>
output : 






Example Use of Color, File content.


<?php
require('fpdf/fpdf.php');

class PDF extends FPDF
{
function Header()
{
    global $title;

    // Arial bold 15
    $this->SetFont('Arial','B',15);
    // Calculate width of title and position
    $w = $this->GetStringWidth($title)+6;
    $this->SetX((210-$w)/2);
    // Colors of frame, background and text
    $this->SetDrawColor(248,123,39);
    $this->SetFillColor(26,69,114);
    $this->SetTextColor(255,255,255);
    // Thickness of frame (1 mm)
    $this->SetLineWidth(1);
    // Title
    $this->Cell($w,9,$title,1,1,'C',true);
    // Line break
    $this->Ln(10);
}

function Footer()
{
    // Position at 1.5 cm from bottom
    $this->SetY(-15);
    // Arial italic 8
    $this->SetFont('Arial','I',8);
    // Text color in gray
    $this->SetTextColor(128);
    // Page number
    $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
}

function ChapterTitle($num, $label)
{
    // Arial 12
    $this->SetFont('Arial','',12);
    // Background color
    $this->SetFillColor(200,220,255);
    // Title
    $this->Cell(0,6,"Chapter $num : $label",0,1,'L',true);
    // Line break
    $this->Ln(4);
}

function ChapterBody($file)
{
    // Read text file
$txt = file_get_contents($file);
    // Times 12
    $this->SetFont('Times','',12);
    // Output justified text 0 is set for whole line.
// If you wants column output then set width for it
    $this->MultiCell(0,5,$txt);
}

function PrintChapter($num, $title, $file)
{
    $this->AddPage();
    $this->ChapterTitle($num,$title);
    $this->ChapterBody($file);
}
}

$pdf = new PDF();
$title = 'Mukund Topiwala Document';
$pdf->SetTitle($title);
$pdf->SetAuthor('Jules Verne');
$pdf->PrintChapter(1,'Mukund Part 1','mukund.txt');
$pdf->PrintChapter(2,'Mukund Part 2','mukund.txt');
$pdf->Output();
?>

output :



fpdf manual and cheatsheet

AddFont(string family [, string style [, string file]])

      Ex. $pdf->AddFont('Comic','I','comici.php');
      family : font family ex times new roman, comic, etc.
      style  : Bold, Italic, Underline
      file   : Name of file for font.

AddPage([string orientation])
      orientation   :  Page orientation. Possible values are (case insensitive):
                                                      ·         P or Portrait
                                                      ·         L or Landscape
                                                     The default value is the one passed to the constructor


Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, int fill [, mixed link]]]]]]])
      w      Cell width. If 0, the cell extends up to the right margin.
      h           Cell height. Default value: 0.
      txt          String to print. Default value: empty string.
           Border Indicates if borders must be drawn around the cell. The value can be either a number:
           ·         0: no border
           ·         1: frame
           or a string containing some or all of the following characters (in any order):
           ·         L: left
           ·         T: top
           ·         R: right
           ·         B: bottom
           Default value: 0.
      ln      Indicates where the current position should go after the call. Possible values are:
           ·         0: to the right
           ·         1: to the beginning of the next line
           ·         2: below
           Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
      Align Allows to center or align the text. Possible values are:
           ·         L or empty string: left align (default value)
           ·         C: center
           ·         R: right align
      Fill  Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
      Link  URL or identifier returned by AddLink().

           Ex. $pdf->Cell(20,10,'Title',1,1,'C');

Close()
      Close pdf document


AliasNbPages([string alias])
      Defines an alias for the total number of pages. It will be substituted as the document is closed.
      alias  The alias. Default value: {nb}.
      
      class PDF extends FPDF{
            function Footer(){
                  //Go to 1.5 cm from bottom
                  $this->SetY(-15);
                  //Select Arial italic 8
                  $this->SetFont('Arial','I',8);
                  //Print current and total page numbers
                  $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
            }
      }
      $pdf=new PDF();
      $pdf->AliasNbPages();


Footer()
      To set the footer
      Ex. See above example

Header()
This method is used to render the page header. It is automatically called by AddPage() and should not be called directly by the application. The implementation in FPDF is empty, so you have to subclass it and override the method if you want a specific processing.
      class PDF extends FPDF{
            function Header(){
                  //Select Arial bold 15
                  $this->SetFont('Arial','B',15);
                  //Move to the right
                  $this->Cell(80);
                  //Framed title
                  $this->Cell(30,10,'Title',1,0,'C');
                  //Line break
                  $this->Ln(20);
            }
      } 

Error(string msg)
This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
FPDF([string orientation [, string unit [, mixed format]]])
This is the class constructor.It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
      orientation   Default page orientation. Possible values are (case insensitive):
                ·         P or Portrait - Default
                ·         L or Landscape
      unit          User measure unit. Possible values are:
                ·         pt: point
                ·         mm: millimeter - Default
                ·         cm: centimeter
                ·         in: inch
A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit. 


      format       The format used for pages. It can be either one of the following values (case insensitive):
                ·         A3
                ·         A4
                ·         A5
                ·         Letter
                ·         Legal
or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).



float GetStringWidth(string s)
      Returns the length of a string in user unit. A font must be selected.
      s    The string whose length is to be computed.

float GetX()
      Returns the abscissa of the current position.

float GetY()
      Returns the ordinate of the current position.

SetX(float x)
Defines the abscissa of the current position. If the passed value is negative, it is relative to the right of the page.
      x  The value of the abscissa.

SetY(float y)
Moves the current abscissa back to the left margin and sets the ordinate. If the passed value is negative, it is relative to the bottom of the page.
      y  The value of the ordinate.

SetXY(float x, float y)
Defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page.

Image(string file, float x, float y [, float w [, float h [, string type [, mixed link]]]])
      Puts an image in the page. The upper-left corner must be given. The dimensions can be specified in different ways:
      ·         explicit width and height (expressed in user unit)
      ·         one explicit dimension, the other being calculated automatically in order to keep the original proportions
      ·         no explicit dimension, in which case the image is put at 72 dpi
      Supported formats are JPEG and PNG. 
      For JPEG, all flavors are allowed:
        ·         gray scales
        ·         true colors (24 bits)
        ·         CMYK (32 bits)
      For PNG, are allowed:
        ·         gray scales on at most 8 bits (256 levels)
        ·         indexed colors
        ·         true colors (24 bits)
      but are not supported:
        ·         Interlacing
        ·         Alpha channel
If a transparent color is defined, it will be taken into account (but will be only interpreted by Acrobat 4 and above). The format can be specified explicitly or inferred from the file extension. It is possible to put a link on the image. 
Remark: if an image is used several times, only one copy will be embedded in the file.

      File     Name of the file containing the image.
      x     Abscissa of the upper-left corner.
      y     Ordinate of the upper-left corner.
      w     Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
      h     Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
      Type  Image format. Possible values are (case insensitive): JPGJPEGPNG. If not specified, the type is inferred from the file extension.
      Link   URL or identifier returned by AddLink().

Line(float x1, float y1, float x2, float y2)
      Draws a line between two points.
      x1  Abscissa of first point.
      y1  Ordinate of first point.
      x2  Abscissa of second point.
      y2  Ordinate of second point.

Link(float x, float y, float w, float h, mixed link)
Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
      x     Abscissa of the upper-left corner of the rectangle.
      y     Ordinate of the upper-left corner of the rectangle.
      w     Width of the rectangle.
      h     Height of the rectangle.
      Link  URL or identifier returned by AddLink().

Ln([float h])
Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
      The height of the break. 
      By default, the value equals the height of the last printed cell.

MultiCell(float w, float h, string txt [, mixed border [, string align [, int fill]]])
This method allows printing text with line breaks. They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other. 
Text can be aligned, centered or justified. The cell block can be framed and the background painted.
      w      Width of cells. If 0, they extend up to the right margin of the page.
      h      Height of cells.
      txt    String to print.
      Border Indicates if borders must be drawn around the cell block. The value can be either a number:
        ·         0: no border - Default
        ·         1: frame
      or a string containing some or all of the following characters (in any order):
        ·         L: left
        ·         T: top
        ·         R: right
        ·         B: bottom
      Align Sets the text alignment. Possible values are:
        ·         L: left alignment
        ·         C: center
        ·         R: right alignment
        ·         J: justification  - Default
      Fill  Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.

Open()
This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.Note: no page is created by this method.
string Output([string name [, string dest]])
Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced. 
The method first calls Close() if necessary to terminate the document.
      Name  The name of the file. If not given, the document will be sent to the browser (destination I) with the name doc.pdf.
      Dest     Destination where to send the document. It can take one of the following values:
      ·         I: send the file inline to the browser. The plug-in is used if available. 
      ·         D: send to the browser and force a file download with the name given by name.
      ·         F: save to a local file with the name given by name.
      ·         S: return the document as a string. name is ignored.
If the parameter is not specified but a name is given, destination is F. If no parameter is specified at all, destination is I.
Note: for compatibility with previous versions, a boolean value is also accepted (false for F and true for D).
int PageNo()
      Returns the current page number.

Rect(float x, float y, float w, float h [, string style])
      Outputs a rectangle. It can be drawn (border only), filled (with no border) or both.
      x     Abscissa of upper-left corner.
      y     Ordinate of upper-left corner.
      w     Width.
      h            Height.

      Style Style of rendering. Possible values are:
        ·         D or empty string: draw. This is the default value.
        ·         F: fill
        ·         DF or FD: draw and fill

SetAuthor(string author)
      Defines the author of the document.
      Author  The name of the author.

SetAutoPageBreak(boolean auto [, float margin])
Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
      Auto       Boolean indicating if mode should be on or off.
      Margin Distance from the bottom of the page.

SetCompression(boolean compress)
Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. 
Compression is on by default. 
Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
      Compress Boolean indicating if compression must be enabled.

SetCreator(string creator)
      Defines the creator of the document. This is typically the name of the application that generates the PDF.
      Creator  The name of the creator.

SetDisplayMode(mixed zoom [, string layout])
Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zooming factor or use viewer default (configured in the Preferences menu of Acrobat). The page layout can be specified too: single at once, continuous display, two columns or viewer default. 
By default, documents use the full width mode with continuous display.
      zoom      The zoom to use. It can be one of the following string values:
        ·         fullpage: displays the entire page on screen
        ·         fullwidth: uses maximum width of window
        ·         real: uses real size (equivalent to 100% zoom)
        ·         default: uses viewer default mode
  or a number indicating the zooming factor to use.
      Layout The page layout. Possible values are:
        ·         single: displays one page at once
        ·         continuous: displays pages continuously  - Default
        ·         two: displays two pages on two columns
        ·         default: uses viewer default mode

SetDrawColor(int r [, int g, int b])
Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
      R    If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255.
      G    Green component (between 0 and 255).
      Blue component (between 0 and 255).

SetFillColor(int r [, int g, int b])
Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
      If g and b are given, red component; if not, indicates the gray level. Value between 0 and 255.
      Green component (between 0 and 255).
      Blue component (between 0 and 255).

SetFont(string family [, string style [, float size]])
Sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document would not be valid. 
The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe). The method can be called before the first page is created and the font is retained from page to page. 
If you just wish to change the current font size, it is simpler to call SetFontSize(). Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this: 
      ·         They are in the current directory (the one where the running script lies) 
      ·         They are in one of the directories defined by the include_path parameter 
      ·         They are in the directory defined by the FPDF_FONTPATH constant
      Example for the last case (note the trailing slash):
define('FPDF_FONTPATH','/home/www/font/');require('fpdf.php');
      family  Family font. It can be either a name defined by AddFont() or one of the standard families (case insensitive):
        ·         Courier (fixed-width)
        ·         Helvetica or Arial (synonymous; sans serif)
        ·         Times (serif)
        ·         Symbol (symbolic)
        ·         ZapfDingbats (symbolic)
      It is also possible to pass an empty string. In that case, the current family is retained.
      Style         Font style. Possible values are (case insensitive):
      ·         empty string: regular
      ·         B: bold
      ·         I: italic
      ·         U: underline
      or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and
ZapfDingbats.
      Size  Font size in points. 

The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12.
//Times regular 12$pdf->SetFont('Times');//Arial bold 14$pdf->SetFont('Arial','B',14);//Removes bold$pdf->SetFont('');//Times bold, italic and underlined 14$pdf->SetFont('Times','BIU');
SetFontSize(float size)
      Defines the size of the current font.
      Size  The size (in points).

SetKeywords(string keywords)
      Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
      Keywords  The list of keywords.

SetLeftMargin(float margin)
      Defines the left margin. The method can be called before creating the first page. 
      If the current abscissa gets out of page, it is brought back to the margin.
      Margin  The margin.

SetLineWidth(float width)
Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
      width  The width.

SetLink(int link [, float y [, int page]])
      Defines the page and position a link points to.
      Link  The link identifier returned by AddLink().
      Y    Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page).
      Page Number of target page; -1 indicates the current page. This is the default value.

SetMargins(float left, float top [, float right])
      Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
      Left     Left margin.
      Top   Top margin.
      Right Right margin. Default value is the left one.

SetRightMargin(float margin)
      Defines the right margin. The method can be called before creating the first page.
      Margin  The margin.

SetSubject(string subject)
      Defines the subject of the document.
      Subject  The subject.

SetTextColor(int r [, int g, int b])
Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
      r    If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255.
      g    Green component (between 0 and 255).
      Blue component (between 0 and 255).

SetTitle(string title)
      Defines the title of the document.
      Title  The title.

SetTopMargin(float margin)
      Defines the top margin. The method can be called before creating the first page.
      Margin  The margin.

Text(float x, float y, string txt)
Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
      x   Abscissa of the origin.
      y    Ordinate of the origin.
      txt  String to print.

Write(float h, string txt [, mixed link])
This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. 
      It is possible to put a link on the text.
      h     Line height.
      txt     String to print.
      link URL or identifier returned by AddLink().
//Begin with regular font$pdf->SetFont('Arial','',14);$pdf->Write(5,'Visit ');//Then put a blue underlined link$pdf->SetTextColor(0,0,255);$pdf->SetFont('','U');$pdf->Write(5,'www.fpdf.org','http://www.fpdf.org');