Easy and free HTML to PDF with PHP

Transforming your html and php webpages into a great PDF it’s going to be super easy from now. Online I googled hundred times a good library to generate PDF dinamically and the only interesting found was the following https://github.com/spipu/html2pdf

I think it’s absolutely the best free lib and it’s very easy to use. It uses composer to manage the dependencies.

If you don’t know what  Composer is or you don’t have access to the php/os  shell because you are in a shared hosting, please refer to my other post.

Here you can find an example:

 * Html2Pdf Library - example
 * HTML => PDF converter
 * distributed under the OSL-3.0 License
 * @package   Html2pdf
 * @author    Laurent MINGUET <webmaster@html2pdf.fr>
 * @copyright 2017 Laurent MINGUET
require_once dirname(__FILE__).'/../vendor/autoload.php';

use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;

try {
    $html2pdf = new Html2Pdf('P', 'A4', 'fr', true, 'UTF-8', array(0, 0, 0, 0));

    include dirname(__FILE__).'/res/about.php';
    $content = ob_get_clean();

    $html2pdf->createIndex('Sommaire', 30, 12, false, true, 2, null, '10mm');
} catch (Html2PdfException $e) {

    $formatter = new ExceptionFormatter($e);
    echo $formatter->getHtmlMessage();

If you are developing an Android app with a WebView which uses this library, I have to inform you that you could have big problems if the php page uses sessions or cookies. I still can’t find the problem but if you find a solution you can post it here!


This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.