HTML to PDF Conversion in CodeIgniter
There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.
I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.
Now, let’s start with implimentation of the code.
Download the TCPDF library code, you can download it from TCPDF wibsite http://www.tcpdf.org/.
Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.
Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file
Helper: application/helpers/pdf_helper.php function tcpdf() { require_once('tcpdf/config/lang/eng.php'); require_once('tcpdf/tcpdf.php'); }
Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.
Controller: application/controllers/createpdf.php function pdf() { $this->load->helper('pdf_helper'); /* ---- ---- ---- ---- your code here ---- ---- ---- ---- */ $this->load->view('pdfreport', $data); }
Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF expample codes as it is in our current controller or view. Now in out current view “pdfreport” copy below given code.
View: application/views/pdfreport.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->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(); // we can have any view part here like HTML, PHP etc $content = ob_get_contents(); ob_end_clean(); $obj_pdf->writeHTML($content, true, false, true, false, ''); $obj_pdf->Output('output.pdf', 'I');
Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,motifications in PDF file by using TCPDF library.
Incredible points. Great arguments. Keep up the
great work.
Thaks a lot.This code helped me a lot.thank u very much……
very good code and working successfully. I have used this to generate pdf invoice
can u send me the code of this..on pushpendrak95@gmail.com
this code is actual working code, which you just need to copy and paste according to the steps given
Hi Buddy Thanks for Code,
as i’m new to codeigniter and php, i’m unable to get the data in the pdf for,
can u send me the code or guide me,
i’m able to generate the pdf but it is empty and showing
“my heading
by Nicola Asuni – Tecnick.com
http://www.tcpdf.org”
as pdf header.
help me our (mdghousesaqlain@gmail.com)
Thanks,
send me your code at pravin@php-guru.in
i have sent you the code
Can you Please send me your code???
You can download it from: https://www.phpclasses.org/package/9465-PHP-CodeIgniter-controller-to-convert-HTML-to-PDF.html
I was searching for this and finally found here. Nice article well explained.
Thanks and keep the good work going. π
Thanks for this tutorial. I like it so much. But what if I want to put CSS in the HTML. Because it didn’t read my css within HTML. Do you have any advice for this?
yes we can integrate CSS in the HTML, you can check the TCPDF example http://www.tcpdf.org/examples/example_061.phps, we can just implement this CSS code in our view (HTML)
HI thanks for this tutorial, it really helps me a lot; BTW is there a way to automatically attach the output file in email?
Thanks in advance
yes it can be done, check google to mail attachment scripts
Excellent! (Y)
Hi! i copy and paste the codes above and follow the instruction but i encountered an error…
this is the error
Fatal error: Call to undefined function tcpdf() in C:\xampp\htdocs\Project\application\views\Template\template1.php on line 2
In controller i only copy and paste the code without adding any codes i simply change the name…
The code in line 2 is just the method ” tcpdf(); “
have you created TCPDF helper and loaded it in cotroller?
have you created TCPDF helper and loaded it in controller?
I cannot make it work. I couldn’t see a pdf file created. In what folder is the pdf file created? Thanks.
It id viewed in browser itself, check in new window or tab
It is viewed in browser itself, check in new window or tab
or you can check the following URL for PDF output
http://www.tcpdf.org/doc/code/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1
Its not preferable to use the helpers directly in views. Instead you can write the functions @ controller and use that in views.
yes it can be done, we can initiate $obj_pdf object in controller and pass it to view to use “writeHTML” method
Really, it’s a good lesson about this library.
HTML Report to PDF files, this is awesome….
May Allah blessing you, π
That’s great work.. I really appreciate it.
But i have one question..
Can we create password protected PDFs through this ? if Yes Than How.
i haven’t tried it yet, you can check http://www.tcpdf.org/ for more details related to TCPDF library
Hello,
Thanks for your tutorial. I just download TCPDF and I am new at CI. Hope your tutorial will helpful for me.
Thanks
Dear Friend,
is your tcpdf that is html to pdf conversion using codeigniter, now working ? if so i really need your help. I tried with the given tutorial, but its showing me the blank pdf. Could you give me the code please, which i can run as demo. Thanking you,
Thanks for this script and that is so easy to use so enjoy this … π
Dear Friend,
is your tcpdf that is html to pdf conversion using codeigniter, now working ? if so i really need your help. I tried with the given tutorial, but its showing me the blank pdf. Could you give me the code please, which i can run as demo or your advices. Thanking you,
are you getting any error?
Thank you for this code.
I am not able to create a pdf using this. i did not get it what should be put on $content place. how can put the html content in this code.
$content is the actual HTML content which you want in PDF
Fatal error: require_once(): Failed opening required ‘tcpdf/config/lang/eng.php’ (include_path=’.:/opt/lampp/lib/php’) in /opt/lampp/htdocs/chooselaweyrs/application/helpers/pdf_helper.php on line 5 error coming in my code
check if this file exist in spefified path “tcpdf/config/lang/eng.php”, else you can download it from TCPDF site
thanku very much sir,
can u tell me how can attach the automated genertae pdf in user mail.
please check the get mail attachment script online
I have two questions:
1. there is no eng.php in new version of TCPDF, also in the site
2. I got so many errors like undefine index: thead, cols, rows, array_push() etc. Is it related to the new version or I should have missed some parts?
Ans. 1) Please download “tcpdf_6_0_080.zip” from http://sourceforge.net/projects/tcpdf/files/
and check the eng.php file here “tcpdf_6_0_080/tcpdf/examples/lang”, according to it change the path in helper file
Ans. 2) May Ans.1) will also resolve this
Please help me how to resolve below error:
TCPDF ERROR: [Image] Unable to get the size of the image: C:\wamp\www\timeTrack_7-4\system\helpers\tcpdf/examples/images/http://localhost:78/timeTrack_7-4/
Images path is taken from your local machine, give absolute path for images
Awesome tutorial, Keep sharing coding stuff. π
Generated code not working in acrobat reader … giving error as “could not open because it is either not a supported file type or file has been damaged”
there may be some improper formatted HTML in the content or something may be outputted before sending it for PDF generation code
its not working,,, my controller function like this
public function pdf() {
$this->load->helper(‘pdf_helper’);
$data[‘skill’] = $this->Cce_model->select_skill();
$data[‘area’] = $this->Cce_model->select_area();
$data=$this->load->view(‘cce/skill_area’,$data,false);
$this->load->view(‘cce/pdfreport’,$data,false);
}
——————————————————
But the i cant get the $data value in the pdfreport.php file
try using this code
public function pdf()
{
$this->load->helper(βpdf_helperβ);
$data[‘skill’] = $this->Cce_model->select_skill();
$data[‘area’] = $this->Cce_model->select_area();
$this->load->view(βcce/pdfreportβ,$data);
}
thank you so much.. π
best tutorial
thanks for this code… how i can get automatic print on that out put pdf..
you cannot directly print from browser, you can check this example on TCPDF website
http://www.tcpdf.org/examples/example_053.pdf
Just Info, this tutorial is working 100% to date π
Thx a lot PravinS!
I see you share interesting things here, you can earn some extra money, your blog has
big potential, for the monetizing method, just search in google
– K2 advices how to monetize a website
Hi PravinS, i did work with above code and it functions correctly. But am getting a blank pdf as output. The content to display in pdf is a view file which contains images, tables and some css content also and i tried to load it. But it doesn’t work. Could you please help me to solve my problem. Thanks in advance.
Here s what am trying to do,
SetCreator(PDF_CREATOR);
$title = “”;
//$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$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();
// we can have any view part here like HTML, PHP etc
// $content = ob_get_contents();
$content=$this->load->view(“n_cv”);
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, ”);
$obj_pdf->Output(‘output.pdf’, ‘I’);
//$this->load(“nurses_cv”);
?>
for images and css you need to do some changes in your code, you can check different examples on TCPDF webslite URL: http://www.tcpdf.org/examples.php
it was the great exp with u guys i have implement your code for HTML & CSS values on PDF black page its working fantastic
Hi Pravin S,
I have set my cutom logo with the function setHeaderData like this:
$this->load->helper(‘pdf_helper’);
tcpdf();
$obj_pdf = new TCPDF(‘P’, PDF_UNIT, PDF_PAGE_FORMAT, true, ‘UTF-8’, false);
$obj_pdf->SetHeaderData(‘../../../assets/img/logo6.png’, 35, $title, PDF_HEADER_STRING);
Pdf is properly display but the logo is missing. I checked the path of the logo as well.. its correct. And its working on my local machine but when i have uploaded on the server then its not working.
Please help me sort out this issue.
Thanks in advanced!!!
check this example: http://www.tcpdf.org/examples/example_003.phps
Hi, pravin , i need to open word file attchment in codeigniter. The thing is, i have a message page where employees can send & recieve messages. They can send attchments along with the messages. The attachment may be pdf, word or images files.I tried a lot to open and read word file attachments. But didnt worked. Please do help me.. Hope you can help me. Thanks in advance.
you can open the PDF and images in browser directly, but for DOC file you will need some plugins, you can check google for the same
thank you.
Thank you so much. This tutorial is totally flawless.
Wow..!! very thanks for this article its fabulous for CodeIgniter in PDF Generation. Its working fine.
really thanks it really helped me and i will surely suggest it to others
Dear Pravin sorry for my English, I’m new in CI and already follow your lesson, which my controller like this :
function print_bankapp()
{
$this->load->helper(‘pdf_helper’);
$id = $this->uri->segment(3);
$row = $this->main_model->getById($id);
if(!$row)
{
redirect(“main”);
}
$data[‘record’] = $row;
$this->load->view(“bankapp_print”,$data);
}
and then put your code for view in application/views/bankapp_print.php, an give html+php code in below ‘// we can have any view part here like HTML, PHP etc’, but when I run the application, came new screen with all of the given code script and result data from $data[‘record’].
What should I do with this ?
send me your code at pravin@php-guru.in
send me your code at manokarti@gmail.com
you just need to copy paste the code from following Url and follow the steps
http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/
hi am trying to folow these tut bt am not getting ma pdf work, here is my controller getting content from my model
function print_installation_pdf()
{
$this->load->helper(‘pdf_helper’);
$data[‘querys’]=$this->install_report_model->install_report();
$data[‘main’]=”reports/pdf_report”;
$this->load->view(‘includes/template’,$data);
}
and here is the view pdf_report
SetCreator(PDF_CREATOR);
$title = “Installation Report”;
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$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();
ob_start();
// we can have any view part here like HTML, PHP etc
$content = file_get_contents($querys);
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, ”);
$obj_pdf->Output(‘output.pdf’, ‘I’);
will b glad for the help n thanks in advance
i have emailed you the code
i can’t find tcpdf/config/lang/eng.php from anywhere. So it says “failed to load pdf document”. Please help me sir.
if you have downloaded tcpdf_6_2_4 version, then it is in “/tcpdf/examples/lang” folder, you can use this path or can move eng.php file to your required path.
Dear All,
Its really an excellent tutorial. But i am faceing little trouble. its delivering me the blank pdf. I am not understanding in the “PDFREPORT.view” in this view, should i mention my actual view name which i want as a pdf ? I really need your kind help and support please.
The Controller
===========
public function transfer_add(){
$this->load->helper(‘pdf_helper’);
sleep(1);
$data=array();
$this->form_validation->set_rules(‘M1500′,”,’callback_check_1500’);
$this->form_validation->set_rules(‘M1510_1’,”,”);
$this->form_validation->set_rules(‘M1510_2’,”,”);
$this->form_validation->set_rules(‘M1510_3’,”,”);
if($this->form_validation->run()==FALSE){
$this->load->view(‘transfer’);
} else {
$data[‘M1500 ‘] =$this->input->post(‘M1500’);
$data[‘M1510_1’] =$this->input->post(‘M1510_1’);
$data[‘M1510_2’] =$this->input->post(‘M1510_2’);
$data[‘M1510_3’] =$this->input->post(‘M1510_3’);
$this->groups_model->add_transfer($data);
$this->load->view(‘pdfreport’, $data);
}
}
The VIEW pdfreport :
=======
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->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();
// we can have any view part here like HTML, PHP etc == ???????????????
===========================================================
$content = ob_get_contents(“transfer”); = HERE should my actual View name be which i want PDF??
============================================
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, ”);
$obj_pdf->Output(‘output.pdf’, ‘I’);
Mr. Pravin,
Its really very nice tutorial. But i have a form with Multiple Page. Can i implement this tcpdf. right now i am getting only the blank PDF page without the content.
I really need your kind advices and help. Looking forward
Dear sir,
I use a tcpdf pdf converter in codeigniter . pdf is not convert and save in path .
$pdf->Output(“$rnd_idf.pdf”,”F”);
is not working and show the error TCPDF ERROR: Unable to create output file: 94609.pdf.
$pdf->Output(“$rnd_idf.pdf”,”F”); is not working.
TCPDF ERROR: Unable to create output file.
I have emailed you the script
Hello Sir,
I am also using TCPDF with codeigniter. Generate PDF fine, but when I save generated PDF file into folder I received this error message -“TCPDF ERROR: Unable to create output file”.
I am using this output code – $obj_pdf->Output(base_url() . ‘upload/’ . $file_name, ‘F’);
Can you give me some idea.
try using only file name instead of file path and second parameter as ‘D’
D: will send to the browser and force a file download with the name given by name.
$obj_pdf->Output($file_name, 'D');
try using only file name instead of file path and second parameter as ‘D’
D: will send to the browser and force a file download with the name given by name.
$obj_pdf->Output($file_name, 'D');
how can i get the submitted information of a form in pdf using this code?
you can submit a form to new page and on that page you can have PDF conversion script
Thanks Man, You saved my ass.
π
Sir could you help me, I need make table on my report but if I use syntax under // we can have any view part here like HTML, PHP etc the report always error. I could make table from $html= <<<EOF but I cant run my php script on there. Please could you give me some advice.
Thanks
sorry I didn’t got what do you mean, you can check different examples at TCPDF website, check this url: http://www.tcpdf.org/examples.php
TCPDF ERROR: Some data has already been output, can’t send PDF file
there is some value you have echoed or some content is there apart from content written in PDF, so you are getting this error
I have an error :
TCPDF ERROR: Some data has already been output, can’t send PDF file
what will I do ?
send me your files at pravin@php-guru.in
Sir i am facing the same problem, Kindly help me out in this :
TCPDF ERROR: Some data has already been output, canβt send PDF file
Don’t know what to do. ?
Help is requested.
Thanks in advance.
There is some value which is echo or printed, which is causing problem…just check the view source, if there is something that you can find
thanks,
want to know how to attach the output file in email?
actually I have not worked on mail attachment, you can check online,
for reference check this url: http://sourceforge.net/p/tcpdf/discussion/435311/thread/e22a8b2f
Hi, I have implemented same way but its not working properly, getting some special char from my firbug console. What is the issue? how can i fix that?
Please help me its an emergency
send me your script at pravin@php-guru.in
No access permission for mail..
My js missing:
$(‘.Download’).on(‘click’,function(){
var lang_id = $(this).attr(“data-lang-id”);
$.ajax({
type : “GET”,
url : “profile_pdf_download”,
dataType: “HTML”,
contentType : “application/html, charset:utf8”,
data :{
‘langs_id’ : lang_id
},
success: function( data ) {
if(data){
window.location.href = data;
}else {
console.log(data);
}
}
});
});
does your JS code is in HTML content whose PDF is to be generated? if yes then it may be creating some problem
hi, one more thin in my view page i have html, there I wil fetch the details from in my database then put loop html then needs to download (force download).
Please help on this regards.
I hope the code is working fine but getting special char and download is not working.
i’ve done all of them. but still, blank. no result in my view page.
but when i didnt use tcpdf, it sent some data(too see if my code was getting data from db), and when i use tcpdf, blank again. help pls….
thx….
send your code at pravin@php-guru.in
Awesome post It help me lot.
Please can I have HTML content in the variable $content.
I mean HTML content like etc….
yes $content can be HTML
I have problems with CSS link.
When I copy and pasthe the content of css files le problem is the same. The pdf file is not propoerly dispaly. I mean the css styles are ignored. Please Help.
you need to add CSS in same page, not using CSS link…for more info plz check http://www.tcpdf.org/examples/example_061.phps
Sir ,
i am new in CI and I have implemented all the code as given above.
when i run the code its shows error page not found.
Please send me the implemented code.
waiting for reply.
You can download it from following links:
Great post
you save me lot of time
thanks a lot
Empty pdf every time, completely empty of any idea, what to do.
Kindly help..
Appreciation in advance for any help.
A 2017 update – 1) I think it is probably better to store the core files in the third_party folder as this is the correct location for them. 2) The lang/eng/config.php file no longer exists and should be something like this:
require_once(APPPATH.’third_party/tcpdf/config/tcpdf_config.php’);
require_once(APPPATH.’third_party/tcpdf/tcpdf.php’);
Thanks for the info, will check and implement the same
Iam getting a blank pdf with no data showing in it
share your code at pravin@php-guru.in