Convert HTML to pdf in php | Techbirds
Posted on: May 22, 2014 /
Categories: PHP / Author Name: Shivek Parmar
In some projects we may need to convert HTML content to PDF for various reasons: transfer, storage, print.
The presentation below will try to guide you how to do it, using PHP.
When available, we concentrate on open-source or free solutions as first choice.
This solution uses DOMPDF project. It simply gets a HTML text and generates a PDF file. Download DOMPDF add it to your projects and you can start coding.
Here is the code that will convert HTML file into PDF file
include(‘dompdf/dompdf_config.inc.php’); global $_dompdf_show_warnings; global $_dompdf_debug; global $_DOMPDF_DEBUG_TYPES; $outfile = ‘test.pdf’; $save_file = TRUE; // Save the file or not $buff = file_get_contents(‘index.html’); $dompdf = new DOMPDF(); $base_path = $_SERVER[‘DOCUMENT_ROOT’].’html2pdf/final8′; $dompdf->load_html($buff); if ( isset($base_path) ) { $dompdf->set_base_path($base_path); } $dompdf->render(); file_put_contents($outfile, $dompdf->output( array(“compress” => 0) )); if (!headers_sent() ) $dompdf->stream($outfile);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
include(‘dompdf/dompdf_config.inc.php’); global $_dompdf_show_warnings; global $_dompdf_debug; global $_DOMPDF_DEBUG_TYPES; $outfile = ‘test.pdf’; $save_file = TRUE; // Save the file or not $buff = file_get_contents(‘index.html’); $dompdf = new DOMPDF(); $base_path = $_SERVER[‘DOCUMENT_ROOT’].’html2pdf/final8′; $dompdf->load_html($buff); if ( isset($base_path) ) { $dompdf->set_base_path($base_path); } $dompdf->render(); file_put_contents($outfile, $dompdf->output( array(“compress” => 0) )); if (!headers_sent() ) $dompdf->stream($outfile); |
The above code will generate the file named with test.pdf on server directory.
To avoid any unexpected rendering issues you should either enable the built-in HTML5 parser (via the DOMPDF_ENABLE_HTML5PARSER
configuration constant) or run your HTML through a HTML validator/cleaner (such as Tidy).
CSS float is not supported (but is in the works, enable it through the DOMPDF_ENABLE_CSS_FLOAT
configuration constant).
Pros:
The DOMPDF is free and open source.
Cons:
The library does not resolve the issue of float elements i.e It does not support float property of CSS. Therefore we have to make our HTML design with tables otherwise the alignment of content in the generated pdf will be affected.
604 total views, 2 views today
Share this On