Create your own helper file to generate PDF in PHP(Codeigniter)


  How to write your own helper file to export grid as PDF in PHP?

                     In my previous post was about “How to generate PDF using PHP”. Today I am writing my own helper file for PDF generation. If you are wondering “How to create your own helper file to generate PDF in PHP(Codeigniter) ?” , Then solution is here. Here I have created single helper file for PDF to export any grid. All you need to do is, you just have to call my helper file and pass your datas as parameter into the function, That’s all done. It will generate PDF as well as you can print PDF file. By doing this you can reuse your code and you don’t have to write much lines of codes. So let’s follow steps to do this stuffs,

 

Step 1:

Download files from dom-pdf and m-pdf and extracts it into your helper folder, ie: /system/helpers/dompdf (or mpdf ).

Step 2:

Now create your own helper and name it pdfexport_helper.php and paste the below lines of code. If you are using mpdf then use below code.




/*
* Subject          : Export pdf using mpdf
* Author           : Sanjoy Dey
* @Created Date    : 10-02-2012
* Version          : CodeIgniter_2.0.3
*
*/

if ( ! function_exists('exportMeAsMPDF')) {

    function exportAsMPdf($htmView, $fileName) 
    {

        $CI =& get_instance();
        $CI->load->library('mpdf51/mpdf');
        // $CI->mpdf=new mPDF('c','A4','','',32,25,27,25,16,13);
        $CI->mpdf->AliasNbPages('[pagetotal]');
        $CI->mpdf->SetHTMLHeader('{PAGENO}/{nb}', '1',true);
        $CI->mpdf->SetDisplayMode('fullpage');
        $CI->mpdf->pagenumPrefix = 'Page number ';
        $CI->mpdf->pagenumSuffix = ' - ';
        $CII->mpdf->nbpgPrefix = ' out of ';
        $CI->mpdf->nbpgSuffix = ' pages';
        $CI->mpdf = new mPDF('', 'A4', 0, '', 12, 12, 10, 10, 5, 5);
        $style = base_url().'/source/template/css/stylesheet.css';
        $stylesheet = file_get_contents( $style);
        $CI->mpdf->WriteHTML($stylesheet,1);                       
        $CI->mpdf->WriteHTML($htmView,2);                       
        $CI->mpdf->Output('mpdf.pdf','I');
     }
  }

If you are using dompdf then use below code.

 
  
/*
* Subject          : Export pdf using dompdf
* Author           : Sanjay
* Version          : CodeIgniter_2.0.3
*/

if ( ! function_exists('exportMeAsDOMPDF')) {

     function exportAsDomPdf($htmView, $fileName) 
     {

         $CI =& get_instance();
         $CI->load->helper(array('dompdf', 'file'));
         $CI->load->helper('file');
         $pdfName = $fileName;
         $pdfData = pdf_create($htmView, $pdfName);
         write_file('Progress Repost', $pdfData);   
     }
}

?>
 
 
Step 3:

Open your controller page and inside your function write below code.



 #Export Function goes here#
 /*This Function is used for Exporting Pdf
  * Author : Sanjay
  */

  $this->load->helper(‘pdfexport_helper.php’);
  $urlId  = $this->uri->segment('3');

    if($urlId == "export") {

       $data['pageTitle'] = "Annual Report";
       $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);
       $templateView  = $this->load->view('../template_export',$data,TRUE);
       exportAsMPdf($templateView,$data['filename']);     
          OR          
       exportAsDomPdf($htmView,$fileName)                                                                 
    }

/* Export Pdf END here */

Step 4:

That’s all you have done all steps. Click in export button to export to PDF and enjoy.

Hope this post will help you a lot to reuse your code and creating your own helper file to generate PDF in PHP(Codeigniter).

Post your queries if you have and share. Keep visiting for new posts here. All the best. Have a good day.

You also can join my group for latest technology updates in below link,

40 comments:

  1. Hello Sunjay,
    It is a nice post about generating pdf files in codeigniter and it will be really helping me as i am developing an invoice system for my site like BambooInvoice.
    I noted one point in your post. For best practices and to avoid problems during updating CI, all third party / own developed helpers and libs should be placed in the application/helpers and application/libraries folders.
    Thank you again for a nice post.

    ReplyDelete
    Replies
    1. Thanks Altaf Hussain....

      You are right. Its a best practice to write your own helper file or libraries to reuse code and to use it globally. If you have anything to share or queries please post here or you can join my developers group also and you can subscribe for new posts as well.

      Keep visiting for new posts.

      Delete
  2. Hi Sanjoy Dey,
    I new to the CodeIgniter .I have a grid view data ,i want to export the pdf .I follow your example but i didn't it showing "Message: Undefined variable: urlid"

    Filename: controllers/Site.php

    i put pdfexport_helper.php this "system\helpers"...
    Can you help me ....

    ReplyDelete
    Replies
    1. Hi !!! Rohit,
      Sure i will help you to solve your problem. I understand your problem. Actually what you have to do is just declare variable call $urlid. First of all pass parameter in url called export after function name. Then get the Uri segment in controller before the condition and store in $urlid.
      Thats it. Pdf will generate.


      Hope Your problem will solve. Let me know here if it is solved.

      With Thanks,
      Sanjoy

      Delete
    2. $urlid = $this->uri->segment('3');
      i declare like this,after that i tryed but it showing blank.can you give clear pls .
      $templateView = $this->load->view('../template_export',$data,TRUE);
      here ../template_export what shoud i give

      Delete
    3. Sanjoy Day
      Can you please to solving the problem .I'm struggling lot .

      Please...

      Delete
    4. Yes Rohit.Definitely i will help you out. You just load your view file which you want to export inside $templateView = $this->load->view('../template_export',$data,TRUE);Then
      From which page you want to export just create one anchor tag and give your url inside href(eg: ) So when you will click that link it will redirect to your function export and in url 'export ' parameter will pass after your function name (eg: http://localhost/development/index.php/userdetails/exportpdf/export) so not inside exportpdf you have to get uri segment like
      $urlid = $this->uri->segment('3'); Thats all done. It will generate pdf.

      Delete
  3. Hi Sanjoy Dey,
    I am very new to CodeIgniter, can you help me...pleas.

    ReplyDelete
    Replies
    1. Follow my code and my instructions which i gave above. Let me know If you have done with. or if any problem you are facing.

      Hope my post will help you.

      With Regards,
      Sanjoy

      Delete
    2. Hi Sanjoy Dey,
      Thanks. My problem Solved...I have doubt about updating record. I am unable to update the record.If you have any example Can you post here.
      Thanks in advanced.

      Delete
    3. Welcome Rohit. What kind of problem you are facing while updating record ??
      You post your Code here. So that i can help you out.

      Delete
    4. hii sanjoy
      i am tring to export ext js grid to pdf i follow your abou code but it's unable to lode library file name
      $this->load->helper(‘pdfexport_helper.php’)
      i created it in helper folder of root folder system
      and another problem is that how can i send here my ext js grid data only so how could i prepare here my view in php

      Delete
  4. Hi Sanjoy Dey,
    How to follow the code igniter to learn clear.Can you have any form or any links can you provide.

    Thanks & regards,
    Rohit.

    ReplyDelete
  5. If You want to learn codeigniter just follow codeigniter user menual first , which available in codeigniter website itself. There is lots of example. And if you want to learn more then that then post your problem here in my site. I will help you out.

    ReplyDelete
  6. Hi Sanjoy dey,
    i am trying to do the login form in codeigniter but i didn't get, it showing the error Can you help me..

    My Controller class:

    function validate_credentials()
    {
    $this->load->model('quiz_mode');
    $query = $this->quiz_mode->validate();

    if($query) // if the user's credentials validated...
    {
    $data = array(
    'admin_name' => $this->input->post('aname'),
    'is_logged_in' => true
    );
    $this->session->set_userdata($data);
    $this->load->view('logged_in_area');
    }
    else // incorrect username or password
    {
    $this->index();
    }
    }

    My model class:

    function validate()
    {
    $this->db->where('admin_email', $this->input->post('email'));
    $this->db->where('admin_password', $this->input->post('pwd'));
    $query = $this->db->get("tvr_admin_dt");

    if($query->num_rows == 1)
    {
    return true;
    }

    }

    My view:

    body
    form action="php echo base_url();index.php/quiz/validate_credentials" method="post"
    table
    Email input type="text" name="email"

    Password input type="password" name="pwd"
    input type="submit" value="submit"
    a href=" php echo base_url(); index.php/quiz/new_user" new user a
    table
    form
    body



    My table name :
    tvr_admin_dt
    table fields
    admin_name
    admin_email
    admin_password

    when i submiting the form it showing

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Quiz::$session

    Filename: controllers/quiz.php

    Line Number: 40


    Can you help me as soon as ,i am struggling past two days
    I hope
    Thanks in advance.

    ReplyDelete
    Replies
    1. Hi !!! Rohit,
      First of all i need to know have you loaded Session Library in Autoload file ? Check it first. Let me know it. If then to you are facing Problem Then Post it or you can Send me mail. I will try to help you.
      Thanks

      Delete
    2. Hi Sanjoy,
      I gave like this in Autoload file
      $autoload['packages'] = array('database','session');

      Can you help me as soon as possiable.
      Thanks.

      Delete
    3. Hi Sanjoy,
      I gave session like in this in Autoload file
      $autoload['libraries'] = array('database','session');

      Delete
    4. ok fine can you send me the files with table as zip format rohit ?
      I will check and try to send you solutions of it.

      Regards,
      Sanjay

      Delete
    5. Sanjoy Dey,
      How can i send .Can you provide your mail id .

      Thanks

      Delete
    6. Yes sure. You can catch me dey.sanjoy0@gmail.com

      Delete
    7. Hi !!! Rohit
      I have checked your code and changed as you wanted.

      Copy the code and replace it into your controller and model page.


      function validate_credentials()
      {
      $email=$this->input->post('email');
      $pwd=$this->input->post('pwd');
      $this->load->model('quiz_mode');
      $session_details= $this->quiz_mode->validate($email,$pwd);


      if(count($session_details) > 0) {

      $userdetails = array(
      'admin_email' => $session_details->admin_email,
      'admin_name' => $session_details->admin_name,
      'is_logged_in' => true
      );

      $this->session->set_userdata($userdetails);
      $this->load->view('logged_in_area');

      } else {

      echo "Invalid username and password!!";
      }

      }

      Model page :


      function validate($email,$pwd)
      {
      $this->db->select('admin_name,admin_email');
      $this->db->where('admin_email', $email);
      $this->db->where('admin_password', $pwd);
      $query = $this->db->get('tvr_admin_dt');

      if($query->num_rows()> 0)
      {
      return $query->row();
      }
      }

      And change in your view page
      Instead of this line

      change into

      session->userdata("admin_name"); ?>


      It is working fine for me. Replace and check it. Hope your problem will solve.
      If you have any other doubt then please post in my discussion board.

      Good Luck!!

      Delete
    8. Hi Sanjoy Dev,
      In my view session it showing error i put the session->userdata("admin_name"); ?>


      A PHP Error was encountered

      Severity: Notice

      Message: Undefined variable: name

      Filename: views/logged_in_area.php

      Line Number: 9

      Can you help me...

      Delete
    9. Hi Sanjoy,
      I have 10 records.I'm trying to Display the records it's ok for me but i want to show the one record in one page(means if u click on any one answer next record will be display).I have attached my view and what i did screen short.Can you give solution for that .I'm waiting for your reply.I raised in your discussion board.
      Can you help sanjoy really i hope
      Please.
      Thanks.

      Delete
    10. Hi !!! Rohit,
      You can do this functionality using ajax and jquery. Once you click in radio button you can post ajax post and check with the database whether selected answer is correct or not ? If correct then in ajax success function you can fetch your next question and answer(Records) and display in next div or in li(If you used ul li).

      Hope this will help you,

      With Regards,
      Sanjoy

      Delete
    11. Hi Sanjoy,
      I'm trying to upload the image path in database but it showing blank page Can you help me .Where i did the mistake .i will send to my view controller and model to ur mail.
      thanks.

      Delete
    12. Hi !!! Rohit,
      I am not clear about your question. As i understand you are uploading image to directory and after that you want to insert or update into database with image path and name. If so Then first Do image upload Then in $_FILES you will get all information which you uploaded. You can get those information and store in variable and insert into database. Thats it. All done.

      Delete
  7. hi Sanjoy,
    Can I ask u about your step 4

    $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);

    What's that means?

    Thank you

    ReplyDelete
    Replies
    1. Hi !!!
      If you look at the line $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE); Where i have loaded my view page(which i want to export) and passed data into view page. and finally i have loaded this view page inside my template page.

      Hope Its clear for you now.


      With Regards,
      Sanjoy

      Delete
  8. hi,

    I have not much knowledge about CI framework.
    Though i understood your code and I want to have like, from the data array that i pass to your function,it directly prints the PDF and ask me to save that file.
    is that possible with this code ?

    Hope to get reply soon,

    Thanks,
    Mrudul Shah

    ReplyDelete
    Replies
    1. Hi !! Mrudul,
      If you want to pass some data array into my helper it can generate and give you the pdf file as you want. For me I created one template page and so that you can reuse your code and I use to pass data with the html page which I want to export as pdf. Thats it It will generate you as you want...

      You can find this is one of the best way 2 create pdf..
      Hope your problem got solved....


      Thanks,
      Sanjay

      Delete
  9. hi,

    I do not understand these two lines of code.

    $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);
    $templateView = $this->load->view('../template_export',$data,TRUE);

    can you please elaborate more on this ?

    Thanks,
    Mrudul Shah

    ReplyDelete
    Replies
    1. Hi !! Mrudul,
      Sorry for late reply. Since I was busy with my work i was not able to reply you earlier.

      In First line I am loading the html view page and passing results into it to display the report and storing it into variable then in second line I am passing the report page into the template page where I have defined my stylesheet and js n all.. Thats it..

      Hope your doubt is clear now. Let me know if you face any other issues.

      With Thanks & Regards,
      Sanjoy Dey

      Delete
  10. I am getting following error: Can you please help? I have extracted dompdf folder in system/helper folder

    Unable to load the requested file: helpers/dompdf_helper.php

    ReplyDelete
    Replies
    1. Hi
      Nice to see your comment. But by seeing the error itself you can find what mistake is there....... Please do check with your code and try to fix. I am here to help everyone but please not small small issues which can be fixed by individual.

      Thank You,

      Delete
  11. Hi,
    Every time it creates a new pdf file. Is there any way to replace the existing one

    ReplyDelete
    Replies
    1. Hi Vinay,
      yes it is creating pdf based on your html view. If I will find any technique to replace existing I will post you.

      Delete
  12. hi , first thanks for your share . I have Question I still don't understand these two lines code $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);
    $templateView = $this->load->view('../template_export',$data,TRUE);
    could you please share the code inside this html view ?

    ReplyDelete
    Replies
    1. In first line $data['htmView'] i am getting the html view page with data passed into it then in second line that html view page passed again into template view page with data from db and finally total html page passed into pdf helper file to generate pdf.

      That's it, very simple. Hope you can understand now...

      Thanks. If you like my posts don't forget to share with others in facebook or some other social network.

      Delete

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved. Powered By- Sanjoy Dey Productions