How to generate pdf file in codeigniter?

Generate pdf in codeigniter v2+ using  tcpdf php library, which will convert codeigniter view file into pdf file. For download tcpdf library file you can check this link. 
For generate pdf file you can follow below steps:
1)  Create tcpdf folder in application\helpers folder.
2)  Add the TCPDF library files in tcpdf folder.
3)  Create new pdf helper file in application\helpers folder and name it pdf_helper.php.
4)  Add below code in pdf_helper.php file:

   function tcpdf()
5)  Then in controller file application/controllers/userpdf.php you can call the pdf library files and for this please check the below code:
    function user_data_pdf()
     $data['query'] =  $this->home_model->home_getall();  
6)  Then in view application/views/user_data_pdf.php in views folder, you will check the below code and see your pdf file in output:
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$title = "PDF Report";
$obj_pdf->SetHeaderData("", "", "User Records", "Hello Admin");
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$tbl_header = '<table border="1" align="center">';
$tbl_footer = '</table>';
$tbl ='<tr class="row-line"><th class="first-cell">Id</th><th>Name</th></tr>';
foreach($query as $row) { 
  $id = $row->id;
  $name = $row->name;
  $tbl .= '<tr><td>'.$id.'</td><td>'.$name.'</td></tr>';
$obj_pdf->writeHTML($tbl_header . $tbl . $tbl_footer, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');

Social Share

Leave a Reply