Posted by Arjun on Thursday 9th October 2014

Generating a PDF in Codeigniter using mPDF

mpdf ci-mpdf

Hey, today I will show you integrating mPDF into CodeIgniter Application. mPDF is a PHP Class, by using this we can easily generate PDF files from HTML Templates.So styling PDF files as easy styling your HTML template as you wish.

Here is the updated post on CodeIgniter 3 - Using mPDF with CodeIgniter 3

Following are the simple steps to use mPDF with CodeIgniter.

Download and extract mPDF

Download mPDF from : and Extract it to your application/third_party/ folder of your CodeIgniter.

Create a new file in your application/libraries/ name it M_pdf.php and copy past the blow PHP Script.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); include_once APPPATH.'/third_party/mpdf/mpdf.php'; class M_pdf { public $param; public $pdf; public function __construct($param = '"en-GB-x","A4","","",10,10,10,10,6,3') { $this->param =$param;
        $this->pdf = new mPDF($this->param);

That is it. You had successfully integrated mPDF in CodeIgniter. Now let's use it.

How to Use

Load the mPDF library just like your load other CI's other libraries and then call pdf property. See the below example code for better understanding.

if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class Welcome extends CI_Controller { 
    public function index() { 
        $data = []; //load the view and saved it into $html variable 
        $html=$this->load->view('welcome_message', $data, true); 

        //this the the PDF filename that user will get to download
		$pdfFilePath = "output_pdf_name.pdf";

        //load mPDF library

       //generate the PDF from the given html

        //download it.
		$this->m_pdf->pdf->Output($pdfFilePath, "D");		
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

That's it.