Codeigniter+DOMPdf

This is how I created my dompf plugin for codeigniter used on most of my projects.

First lets start off with the files, get a copy of dompdf and extract the files needed.

Here’s what you’ll need.
on your CI System/plugins Directory make a folder and call it something, I named mine “dompdf” extract the following folders and files from dompdf.

system/plugins/dompdf/

  • include (entire directory)
  • lib (entire directory)
  • dompdf.php
  • dompdf_config.inc.php
  • LICENSE.LGPL (for legality sake :P )
  • load_font.php

Now lets move on and create your plugin under the system/plugin folder and call it something, I baptized mine as “to_pdf.php“.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Try increasing memory available, mostly for PDF generation
 */
ini_set("memory_limit","32M");

function pdf_create($html, $filename, $stream=TRUE)
{
	require_once(BASEPATH."plugins/dompdf/dompdf_config.inc.php");

	$dompdf = new DOMPDF();
	$dompdf->set_paper("a4", "portrait");
	$dompdf->load_html($html);
	$dompdf->render();
	if ($stream) { //open only
		$dompdf->stream($filename.".pdf");
	}else{ // save to file only, your going to load the file helper for this one
		write_file("pdf/$filename.pdf", $dompdf->output());
	}
}
?>

Usually I render from HTML to PDF so we’re gonna need an HTML file for this one. Here’s my structure and i called it sample.html:

<html>
	<head>
		<title>PDF Sample</title>
		<script type="text/php">
		if ( isset($pdf) ) {
			//This goes to the header
			$font = Font_Metrics::get_font("Helvetica", "bold");
			$pdf->page_text(72, 18, "Page {PAGE_NUM} of {PAGE_COUNT}", $font, 8, array(0,0,0));

			//get started with the footer
			// Open the object: all drawing commands will
			// go to the object instead of the current page
			$footer = $pdf->open_object();
			$text_height = 7;

			$w = $pdf->get_width();
			$h = $pdf->get_height();
			$y = $h - 2 * $text_height - 24;
			$size = 7;
			$color = array(255,255,255);

			$font = Font_Metrics::get_font("Helvetica", "italic");
			$text = "http://www.ikawka.com/ - ".date("F m, Y - h:i:s a");
			$width = Font_Metrics::get_text_width($text, $font, $size);

			// Add a logo
			$img_w = 540; // 2 inches, in points
			$img_h = 20; // 1 inch, in points -- change these as required

			$pdf->image("images/logo.png", "png", ($w - $img_w) / 2.0, $y - $img_h, $img_w, $img_h );
			$pdf->text(38, $y-16, $text, $font, $size, $color);
			// Close the object (stop capture)
			$pdf->close_object();

			// Add the object to every page. You can
			// also specify "odd" or "even"
			$pdf->add_object($footer, "all");
		}
		</script>
	</head>
	<body>
		<h1>Hello Gallaxy!!!</h1>
	</body>
</html>

I’ve added some extra feat onto this one, the script on the HTML file will have a header and a footer image on each and every page of the generated pdf.

Now let’s make our controller. Let’s name it “htmltopdf.php“.

<?php
class htmltopdf extends Controller{
	function htmltopdf(){
		parent::Controller();
	}

	function index(){
		$this->load->library( 'parser' );
		$this->load->plugin( 'to_pdf' );

		//render your html first, I'm using parser on this example
		//you can always use any method you like
		$html = $this->parser->parse('sample.html', $data, true);

		pdf_create( $html, 'filename', TRUE ); //this will stream only
	}
}
?>

And there you have it, your dompdf magic! ^_^

Extras: (download at your own risk)
dompdf – minor bug fixes.

33 comments

  1. Hi!!!
    how I can send data collected from a database ?, in this case to sample.html

    • note this line:
      $html = $this->parser->parse(’sample.html’, $data, true);
      put some data in the $data variable

      like so:
      $data['somedata'] = ‘This is some data’;
      $html = $this->parser->parse(’sample.html’, $data, true);

      now on your sample.html:
      <html>

      <body>
      {somedata} < — this will be replaced by the parser
      </body>
      </html>

  2. Roshan

    Hello,

    Thanks for sharing your idea..
    But I am getting an error message(I am using Mozzila) that says.
    “Connection Interrupted
    The document contains no data.
    The network link was interrupted while negotiating a connection. Please try again.”
    I am just struck at this place..
    I have placed htmltopdf.php in the controllers folder and in this php file I have added this code $this->load->view(’sample.html’); and copied sample.html file in views folder.

    Please let me know if I am doing anything wrong or what should be done to solve this issue ASAP…Thanks

    • ikawka

      can you paste your code? so that I will have a good view on it. ^_^

      • Roshan

        Hi,
        I have used the same code as yours.I just wanted to see how it works..

        load->library( ‘parser’ );
        $this->load->plugin( ‘to_pdf’ );
        //Here I added few lines.

        $this->load->view(’sample.html’);
        $data['test']=’Testing Text’;
        //my extra code ends here.
        $html = $this->parser->parse(’sample.html’, $data, true);
        pdf_create( $html, ‘filename’, TRUE ); //this will stream only
        }
        }
        ?>

        And in Sample.html page I replaced “Hello Galaxy” text in body section with {test}

        Only this much of change and I followed all your step.

  3. Alfredo

    Roshan,

    Make sure you are using PHP 5 or above.

  4. Hello All,

    Just a small doubt do we need to make any changes if we are working on Windows environment or in Linux??

    • nope, nothing special, OS doesn’t matter; nothing that I know of so far.

  5. congratulations! this post is very useful!

    I tried to use and did not include the header and footer

    in execution the inside is not interpreted and $pdf variav

    There is something special to be done?

    thanks!

  6. Congratulations! This post is very useful!

    I tried to use and did not include the header and footer… In execution the inside is not interpreted and $pdf variable is not content

    There is something special to be done in header and footer?

    Thanks!

    • Put some content into the body so that you will have an output, make sure you got php5+

  7. miss_amylee

    hy.. im stil having ‘connection interrupted’ by using dis code.anyone pls help me..al soltn above i already tried.but seems same prob occured

  8. Hi,

    Thank you for your nice doc.
    But I am facing some problem with Japanese character. Its become mojibake (?????). would you please give me some idea.

    Best regards
    Jami

  9. I don’t know exactly but u need to convert a font that supports those characters to .afm and update the dompdf_font_family_cache.dist with the new font installed. take note, that for the fonts to appear on the client side, the client’s machine must have the same font. i’ve successfully done this with some dingbat font i needed to use on some project.

  10. Hey how can I add header & footer?

  11. What type of CSS is allowed in the sample.html? Will it covert all CSS to the PDF? Also can you add some documentation on how to create headers and footers?

  12. nice work..its very useful..

  13. Tomas Barrios

    Hi! Great article. This library works incredible for me. Now, I am trying to get to work the header insertion without any success. =(

    I am not using the parser, instead i am loading a view like this:
    $html = $this->load->view(‘productos/ficha_pdf’, $data, true);

    Could that be the problem?

    Thanks!

  14. Tomas Barrios

    Hey, great article!. I could manage to create a PDF but no luck with the header and footer, just getting blank content in that area. Any ideas about this?

    Thanks!

  15. Great tutorial. Plugins don’t work in CodeIgniter 2.0, So I tweaked your code a bit to make it work with helpers. Anyhow, thanks a ton!

  16. How to make 3 page using dompdf?

    content of every page is only one line.
    thanks

  17. how to make 3 pages using dompdf?

    content of every page is only one line.

    how to use page-break using dompdf? thanks

  18. how to make 3 pages using dompdf?

    content of every page is only one line.

    how to use page-break using dompdf? thanksm

  19. hi im using dompdf as helper, is whats the difference?
    i cant display any images

    pls reply thanks

  20. i used this as helper, instead of plugin, is there a difference,

    also, there is no folder “plugin” under my system folder

  21. ikawka

    Ok, here’s my shot, try displaying the view first without converting it to pdf, and see what happens see if you have a display, and if not you work from there first, then move on.
    //——————————-
    $load->library( ‘parser’ );
    $this->load->plugin( ‘to_pdf’ );
    //Here I added few lines.
    $data['test']=’Testing Text’; //note the switching of lines; this should come first
    $this->load->view(’sample.html’);
    //my extra code ends here.
    //$html = $this->parser->parse(’sample.html’, $data, true);
    //pdf_create( $html, ‘filename’, TRUE ); //this will stream only

  22. Roshan

    Hi Dude.

    I tried..It’s able to parse and display on Browser but not able to generate Pdf….

  23. ikawka

    pdf_create( $html, ‘filename‘, TRUE );
    in the ‘filename‘ < — change it with your “folder/filenamehere.pdf” you should have the appropriate permission on that folder to write a file.

  24. Alfredo

    Roshan,

    dompdf works with PHP 5 or above. I got that same error when I tried using dompdf in PHP 4.

  25. esta libreria no funciona en php4 alguno de ustedes tendra alguna solucion para este que funcione en php4 ?

  26. Lo siento mucho, pero esta biblioteca se construye usando php5 solamente.

Leave a Reply