DEV Community

It's Just Nifty
It's Just Nifty

Posted on • Originally published at niftylittleme.com on

How To Convert HTML To PDF With PHP

(Guide For Windows. Not Mac or Linux)

Unsplash Image by Christopher Gower

(Image Source)

There's more than one way to convert HTML to a PDF in PHP. You can use Dompdf or Mpdf; however, there is a difference in how these two libraries are doing it.

Note: Not all solutions will be in this article.

To use both these libraries, you will need Composer.

Converting HTML To PDF With Dompdf

I also show the code in the article discussing why the PDF sometimes won't open when using Dompdf.

    <?php
        require 'vendor/autoload.php';

        // reference the Dompdf namespace
        use Dompdf\Dompdf;

        $content = '<h1>Hello World</h1>';

        // instantiate and use the dompdf class
        $dompdf = new Dompdf();
        $dompdf->loadHtml($content);

        // (Optional) Setup the paper size and orientation
        $dompdf->setPaper('A4', 'landscape');

        // Render the HTML as PDF
        $dompdf->render();

        ob_end_clean();

        // Output the generated PDF to Browser
        $dompdf->stream();
    ?>
Enter fullscreen mode Exit fullscreen mode

With this code, the PDF is downloaded.

Converting HTML To PDF With Mpdf

<?php
    require_once __DIR__. '/vendor/autoload.php';
    use Mpdf\Mpdf;
    $mpdf = new Mpdf();
    $mpdf->WriteHTML('<h1>Hello world! Hi</h1>');
    $mpdf->Output();
?>
Enter fullscreen mode Exit fullscreen mode

With this code, the PDF is opened in the browser when you navigate to your file (Example: localhost/test1.php)

Top comments (0)