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 http://www.tcpdf.org/ 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:
<?php
function tcpdf()
{
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
}
?>
5) Then in controller file application/controllers/userpdf.php you can call the pdf library files and for this please check the below code:
<?php
function user_data_pdf()
{
$data['query'] = $this->home_model->home_getall();
$this->load->helper('pdf_helper');
$this->load->view('user_data_pdf',$data);
}
?>
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:
<?php
tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
//$obj_pdf->SetTitle($title);
//$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$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->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
$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>';
}
ob_end_clean();
$obj_pdf->writeHTML($tbl_header . $tbl . $tbl_footer, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');