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: , , , , ,

7 Responses

  1. fr3ak says:

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

  2. Ruchir Babbar says:

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

  3. Deepak Mittal says:

    Most welcome.

  4. Ruchir Babbar says:

    Can this script also handle nested tables?

  5. Deepak Mittal says:

    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.

  6. Zahid says:

    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.

Leave a Reply