Absolutely Tech

[HowTo] Convert HTML to PDF using PHP


In a recent project, I had to output to a PDF file as well as to the browser. For this purpose first I downloaded the library from here. Then this code:

<?php
 
ob_start();  //Start buffering the output
 
//your coding starts here
 
....
 
....
 
...
 
...
 
//Coding ends here
 
$html = ob_get_contents(); //dumb the buffer as a string in variable $html
 
ob_flush();  //Output the buffer to browser
 
//Start outputting to PDF
 
define('HTML2FPDF_VERSION','3.0(beta)');
define('RELATIVE_PATH','fpdf/');
define('FPDF_FONTPATH','font/');
 
require_once(RELATIVE_PATH.'fpdf.php');
require_once(RELATIVE_PATH.'htmltoolkit.php');
require_once(RELATIVE_PATH.'html2fpdf.php');
$pdf = new HTML2FPDF();
$pdf->WriteHTML($html);
$name="doc.pdf";
$pdf->Output($name);
 
?>

When you run this script, you’ll get a pdf file “doc.pdf” in your script directory with the output of the current script.

For outputting something else other than the current script:

<?php
 
//Your code
 
....
 
....
 
....
 
// To make a pdf file:
 
$html= "<h1>hello</h1>";  //To add more html code use $html.= yourcode; in the next line
 
define('HTML2FPDF_VERSION','3.0(beta)');
define('RELATIVE_PATH','fpdf/');
define('FPDF_FONTPATH','font/');
 
require_once(RELATIVE_PATH.'fpdf.php');
require_once(RELATIVE_PATH.'htmltoolkit.php');
require_once(RELATIVE_PATH.'html2fpdf.php');
$pdf = new HTML2FPDF();
$pdf->WriteHTML($html);
$name="doc.pdf";
$pdf->Output($name);
 
?>

Category: How-To, PHP, Programming, Tips and tricks, Web development

Tagged: , , , , ,

  • http://freakingtips.com fr3ak

    Tried that a long time ago but gave an error with table inside tables. Didn’t work well for spans and etc.

  • http://freakingtips.com fr3ak

    Tried that a long time ago but gave an error with table inside tables. Didn’t work well for spans and etc.

  • http://www.techmindz.com Deepak Mittal

    @fr3ak:
    That library is much better now. Shouldn’t give errors with nested tables now.

  • http://www.techmindz.com Deepak Mittal

    @fr3ak:
    That library is much better now. Shouldn’t give errors with nested tables now.

  • Ruchir Babbar

    THANK YOU!!!!!!
    This was really helpful.

  • Deepak Mittal

    Most welcome.

  • Ruchir Babbar

    Can this script also handle nested tables?

  • Deepak Mittal

    Yes, it does handle nested tables. Please check out the documentation and support forums of the html2fpdf library for more information about its features and capabilities.

  • Zahid

    i used this library few days earlier, but it does not handle nested tables.
    gave no error on nested tables but cannot show original html bcoz of nested tables.

  • Zahid

    i used this library few days earlier, but it does not handle nested tables.
    gave no error on nested tables but cannot show original html bcoz of nested tables.

Ubuntu 11.04

The next version of Ubuntu is coming soon

Follow me

Sponsors