Hi Geeks,
Today I am Sharing you the code for making pdf or download pdf files in codeigniter. In this Code snippet we have used the MPDF Kit for generating pdf of html views or dynamic templates. So Following are the steps to create/convert HTML to PDF In Codeigniter using MPDF
Prerequisites :- GD LIBRARY SHOULD BE ACTIVE ON YOUR WEB SERVER
Step 1: Download the Mpdf Class and methods from here or https://www.mediafire.com/?9qmqaw2yqlo5caa
Now extract the zip file and put the mpdf folder to application >> third_party folder (this folder Exists in Application folder in codeigniter app )
Step 2. Now make a ci library to call/communicate the mpdf methods and classes from your ci controllers
Now go to libraries folder in application folder and create a file named : M_pdf.php having following code snippet.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class m_pdf { function m_pdf() { $CI = & get_instance(); log_message('Debug', 'mPDF class is loaded.'); } function load($param=NULL) { include_once APPPATH.'/third_party/mpdf/mpdf.php'; if ($params == NULL) { $param = '"en-GB-x","A4","","",10,10,10,10,6,3'; } //return new mPDF($param); return new mPDF(); } }
Step 3: Now in any of your controller where you want to use or convert the view to pdf output
You can see the calling of our created libary by loading the libarray using this->load_library, and pass the data whatever you required in your view or get the data from model and just pass to your pdf view and use/render that data in your view just like a normal view and controllers.
for sample , We have created a method named save_download having following code
public function save_download() { //load mPDF library $this->load->library('m_pdf'); //load mPDF library //now pass the data// $this->data['title']="MY PDF TITLE 1."; $this->data['description']=""; $this->data['description']=$this->official_copies; //now pass the data // $html=$this->load->view('pdf_output',$this->data, true); //load the pdf_output.php by passing our data and get all data in $html varriable. //this the the PDF filename that user will get to download $pdfFilePath ="mypdfName-".time()."-download.pdf"; //actually, you can pass mPDF parameter on this load() function $pdf = $this->m_pdf->load(); //generate the PDF! $pdf->WriteHTML($html,2); //offer it to user via browser download! (The PDF won't be saved on your server HDD) $pdf->Output($pdfFilePath, "D"); }
By using this code you will able to make a functionality to convert html to pdf in codeigniter:
If you face any struggle in this please Comment below – Thanks & Cheers 🙂