Luutaa Technologies - Developer Blog

Generating a PDF in CodeIgniter using MPDF

Many times we need to generate reports in our applications it may be in the form of charts, excel sheets, or PDF.

I assume that you are at an intermediate level and able to generate the report in HTML form and now only facing problem to convert it into PDF format.

Here we are going to Generate a report in PDF format. There are many libraries available for these purpose like FPDF, PDF etc. In our case i used MPDF and CodeIgniter version 2.1.2 .  you can download MPDF from here .

Now, you need to extract the MPDF and put all the files at ./application/helpers/mpdf.  We have to create a custom helper. Here i create a helper file as /application/helpers/My_Pdf_helper.php. The code will be as follows :

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('create_pdf')) {

    function create_pdf($html_data, $file_name = "") {
        if ($file_name == "") {
            $file_name = 'report' . date('dMY');
        }
        require 'mpdf/mpdf.php';
        $mypdf = new mPDF();
        $mypdf->WriteHTML($html_data);
        $mypdf->Output($file_name . 'pdf', 'D');
    }

}

Now You need to use this helper into your controller and use into function.
And the function will be look like as follows :-

public function pdf_report(){
 $this->load->helper(array('My_Pdf'));   //  Load helper
 $data = file_get_contents(site_url('controller/file')); // Pass the url of html report
 create_pdf($data); //Create pdf
 }

This function will directly download the pdf file.

Leave a Reply:

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