PDF's with CodeIgniter 2.1

by Filip Lundby.

CodeIgniter is an open source MVC PHP-framework. In this guide I'll show how to generate PDF-files combining CodeIgniter with fpdf.org.

  1. Download fpdf
    Go to fpdf.org and download the newest version of fpdf (current version is 1.7). Unzip the file.

  2. Copy fonts
    Place the font-folder in the root-directory of CodeIgniter.

  3. Copy class
    Place the class-file fpdf.php in application/libraries.

  4. Create a new class
    Still in application/libraries create a new file called pdf.php and copy following code into the file:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    require('fpdf.php');
    class Pdf extends FPDF
    {
      // Extend FPDF using this class
      // More at fpdf.org -> Tutorials
      function __construct($orientation='P', $unit='mm', $size='A4')
      {
        // Call parent constructor
        parent::__construct($orientation,$unit,$size);
      }
    }
    ?>
  5. Create a new controller
    In application/controller create a new file called doc.php and copy the following into the file:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class Doc extends CI_Controller {
      function __construct()
      {
        parent::__construct();
        $this->load->library('pdf'); // Load library
        $this->pdf->fontpath = 'font/'; // Specify font folder
      }
      public function index()
      {
        // Generate PDF by saying hello to the world
        $this->pdf->AddPage();
        $this->pdf->SetFont('Arial','B',16);
        $this->pdf->Cell(40,10,'Hello World!');
        $this->pdf->Output();
      }
      // More methods goes here
    }
    ?>
  6. Done!
    That's about it. More examples at fpdf.org

Leave some feedback