2/28/12

Generating PDF files from Database using CodeIgniter

Before we start here is a brief information about CodeIgniter. CodeIgniter is an open source web application framework built for PHP coders who want to develop a full-feature web application. It has libraries which help us to perform many tasks very easily. It works on the MVC Pattern.



As a programmer I find PDF files very helpful to me when generating reports and getting them printed.

We will be using R&OS pdf class. I find this to be the best one because all others libraries I came across didn't offer me a good control over the making of the file and also the process of making i.e the code required for this library is bit tricky but it helped me improve my coding.

Lets Start :


Before we start, make sure you have downloaded the zip file and if not download it. Unzip/ extract the files and folders. 

We will be loading data for our pdf file from our mysql database. So make sure you have configured the your database. To make your database work goto the config folder and in that open the database.php and fill in the details about your DB.

After extraction is done, you will find two files namely class.ezpdf.php/cezpdf.php and class.pdf.php. Now put these two .php files inside application/libraries. To make these work within CI you will have to a modification in the cezpdf.php/class.ezpdf.php. The modification is to be done in the include statement : 


include_once(APPPATH . 'libraries/class.pdf.php');

Now go to your controller folder and there make a new file name generate.php and pdf_helper.php.

pdf_helper.php :


<?php

function prep_pdf($orientation = 'portrait')
{
    $CI = & get_instance();
    
    $CI->cezpdf->selectFont(base_url() . '/fonts');    
    
    $all = $CI->cezpdf->openObject();
    $CI->cezpdf->saveState();
    $CI->cezpdf->setStrokeColor(0,0,0,1);
    if($orientation == 'portrait') {
        $CI->cezpdf->ezSetMargins(50,70,50,50);
        $CI->cezpdf->ezStartPageNumbers(500,28,8,'','{PAGENUM}',1);
        $CI->cezpdf->line(20,40,578,40);
        $CI->cezpdf->addText(50,32,8,'Printed on ' . date('m/d/Y h:i:s a'));
        $CI->cezpdf->addText(50,22,8,'PDF Tutorial - www.code2learn.com');
    }
    else {
        $CI->cezpdf->ezStartPageNumbers(750,28,8,'','{PAGENUM}',1);
        $CI->cezpdf->line(20,40,800,40);
        $CI->cezpdf->addText(50,32,8,'Printed on ' . date('m/d/Y h:i:s a'));
        $CI->cezpdf->addText(50,22,8,'PDF Tutorial - www.code2learn.com');
    }
    $CI->cezpdf->restoreState();
    $CI->cezpdf->closeObject();
    $CI->cezpdf->addObject($all,'all');
}

?>

generate.php :


<?php

class Generate extends CI_Controller
{

    function Generate()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
    }


    function create()
    {

                $this->load->library('cezpdf');

        $this->cezpdf->ezText('PDF REPORT OF LOGIN TABLE', 12, array('justification' => 'center'));
        $this->cezpdf->ezSetDy(-10);
                $i=1;
                $content="";

                $fname="";
                $query = $this->db->query('SELECT * FROM table_name');
                $num = $query->num_fields();
                $farr=array();

                while($i <= $num){
                    $test = $i;
                    $value = $this->input->post($test);

                    if($value != ''){
                            $fname= $fname." ".$value;
                            array_push($farr, $value);

                        }
                     $i++;
                }

                $fname = trim($fname);

                $fname=str_replace(' ', ',', $fname);
                $this->db->select($fname);
                $query = $this->db->get('table_name');
                $result = $query->result();

                foreach ($farr as $j)
                {

                    $content= strtoupper($j)."\n\n";
                    foreach($result as $res){
                       $content = $content.$res->$j."\n";
                    }

                      $this->cezpdf->ezText($content, 10);

                       $this->cezpdf->ezStream();
                 }

    }


In the above, first thing we do is load the R&OS library for use. Next we use the ezText() function to create a title for our document. This function takes the text it will display as the first argument, the size of that text and an optional array of additional configuration options. 

After the whites pace we put the rest of the content for the document in a variable called $content and add it to our document using the ezText() function again. Finally, we create our document using the ezStream() function which actually creates the document and sends it to the users which prompts them to view/download the generated PDF document.

SHARE THIS POST:

20 comments:

  1. You can use TCPDF library also, refer this:
    http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/

    ReplyDelete
    Replies
    1. Yes Pravin we can use the library also. But as stated I chose R&OS pdf class because it offered me more control plus helped me improve my coding.

      Delete
  2. Hi,
    where i can download R&OS zip file please send me link , i am clicking this link "http://www.ros.co.nz/pdf/" but unable to download .

    ReplyDelete
    Replies
    1. Here is one link: http://pdf-php.sourceforge.net

      I changed in the post too

      Delete
  3. This Link is not working !!!! Please direct me to a working link.....!!!

    ReplyDelete
    Replies
    1. Here is one link: http://pdf-php.sourceforge.net

      Delete
    2. That link is not use so send new

      Delete
  4. Very good tutorial

    ReplyDelete
  5. With smartphone and other handheld devices are mostly used for accessing internet, it is important to have responsive website for your business that go comfy on all devices with dissimilar screen resolution.
    You can check my PHP Training site for more details.

    ReplyDelete
  6. Hi I am new to PHP development... I used the above code but I am getting blank page while calling the controller in URL.. Please help me to generate the PDF file

    ReplyDelete
  7. Please send zip download url

    ReplyDelete
  8. Please send me the souece code . I am not able to execute this ...... thanks in advance

    ReplyDelete

  9. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android training in chennai

    ReplyDelete
  10. In this article informative blog create well and it's Android SDK it creates a future stunning mobile application and it's enhanced web apps priority. It's used for basic Java coding with creating mobile apps stunning informationSelenium Training in Chennai
    Android Training in Chennai

    ReplyDelete