Home » Create PDFs in PHP using FPDF Library

Use Free PDF (FPDF) PHP class to easily generate pure PHP PDF files. Options include displaying the generated PDF file on the browser, or saving the created PDF file on a LOCAL directory, and another is forcing a download of the generated PDF file.

Requirements:

  • Composer
  • PHP ^PHP 5.1
  • PHP Zlib
  • PHP GD

Step 1.

Setup dependencies.

{
    "require": {
        "setasign/fpdf": "^1.8"
    }
}

Step 2.

Install FPDF.

$ composer install

Step 3.

Create a new PHP file and name it create-pdf-files-in-php.php and copy paste the code below.

The objective is to create a basic PDF file and display the generated PDF file on a browser.

<?php

// Load dependencies
require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Cell(40, 10, 'Hello World !');
$pdf->Output();

Result.

The next goal is to create a basic PDF file (hello-world.pdf) and save the generated PDF file to the server.

<?php

// Load dependencies
require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Cell(40, 10, 'Hello World !');
$pdf->Output('F', 'hello-world.pdf');

Result.

The file (hello-world.pdf) was created.

Another target is to create PDF file and force or auto download the generated PDF file.

<?php

// Load dependencies
require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',16);
$pdf->Cell(40, 10, 'Hello World !');
$pdf->Output('D', 'hello-world.pdf');

Result.

The file (hello-world.pdf) was automatically downloaded.

Notes:

  • This tutorial is created with composer, but the dependency files can also be downloaded directly from the developers website (http://www.fpdf.org/).
  • Make sure the path to the dependency file (fpdf.php) is correct.
    // Load dependencies
    require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');
  • Displaying the generated PDF file directly to the browser requires the Output() to be empty.
    $pdf->Output();
    
  • Saving the generated PDF file to a local directory requires the 'F' parameter and the path and name of the file.
    $pdf->Output('F', 'hello-world.pdf');
    

Forcing a download of the generated PDF file requires the 'D' parameter and the path and name of the file.

$pdf->Output('D', 'hello-world.pdf');

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *