PDF generation using dompdf

Sean Gates edited this page Aug 30, 2014 · 33 revisions
Clone this wiki locally

Category:Plugin::Data Conversion

Well... its not so much of a helper as a "how-to". I've needed to be able to generate PDFs on the fly for the application I'm building. I've played with FPDF but found it the syntax too onerous to be practical (I want users to be able to control the look of their PDFs, and with FPDF they'd essentially need to learn a new language). So then I tried html2fpdf to create them on the fly from HTML pages. I was very, very disappointed with its lack of support for simple HTML. I then found xhtml2pdf and html2ps... same thing. Finally, I hit upon dompdf. EXCELLENT! Decent support for what I needed to do, and has decent (not great) support for many CSS styles and XHTML.

So here's how to implement it in your own project.

  1. Get a copy from https://github.com/dompdf/dompdf

  2. Uncompress it. You'll get a folder (I renamed it "dompdf"), and put the whole thing into your plugins folder, ie: /system/helpers/dompdf

  3. Create the plugin. I've named it "dompdf_helper.php"

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE) 
    $dompdf = new DOMPDF();
    if ($stream) {
    } else {
        return $dompdf->output();
  1. use it in your controllers like this
function pdf()
     $this->load->helper(array('dompdf', 'file'));
     // page info here, db calls, etc.     
     $html = $this->load->view('controller/viewfile', $data, true);
     pdf_create($html, 'filename');
     $data = pdf_create($html, '', false);
     write_file('name', $data);
     //if you want to write it to disk and/or send it as an attachment    

A few notes:

  • It is PHP 5 only. Sorry, I know that goes against what CI is doing here... but the level of support for CSS in the other projects wasn't acceptable for my app
  • You might find that there is limited or no support for a specific CSS style you want (ie: floating) and you'll need to work around with old-school tables. Ugh ..... Sorry for that...
  • I in no way can claim credit for writing this fine code. dompdf was released under an lgpl license, and you'll obviously need to respect that in your apps if you choose to use it.

Based on my forum post at http://www.codeigniter.com/forums/viewthread/45118/

*Another small note:


needed if you use write_file()