Wednesday 23 November 2011

Creating PDF files with Codeigniter

Generating PDF files is required for saving and printing the documents like invoices or something.

The task is easy with free pdf generation libraries like dompdf, mpdf, fpdf etc.
Below is the code for generating pdf from html using mpdf library.
First extract mpdf files in codeigniter /library/mpdf53.

private function _gen_pdf($html,$paper='A4')
    {
        $this->load->library('mpdf53/mpdf');               
        $mpdf=new mPDF('utf-8',$paper);
        $mpdf->WriteHTML($html);
        $mpdf->Output();
    } 



To use the code below to simply redirect the output to the function as:


public function doprint($pdf=false)
    {
        $this->load->library('parser');
        $data = $this->data->getdata();       
        $output = $this->parser->parse('form',$data,true);   
        if ($pdf=='print')
            $this->_gen_pdf($output);
        else
            $this->output->set_output($output);               
    }



This will generate the pdf file within the browser.