Convert HTML To PDF In PHP

In this tutorial-based article, we will learn how to convert HTML with CSS styling into a PDF file. Whilst PHP currently doesn’t have this capability in its native functional arsenal. We will utilise a third-party library to achieve the conversion.

The conversion library of choice (html2pdf) is free to use, allows modification, and even redistribution. So if you’re in a commercial environment, it’s a bonus. The package not only converts HTML syntax to PDF files but brings along the CSS styling too.

Convert HTML to PDF

Please note that html2pdf works with PHP versions from 5.6 to 7.4 which gives it a great scope for old projects too.

Let’s go ahead and install the package and convert some HTML.

html2pdf HTML to PDF converter can be installed manually by downloading the files from its GitHub repository or alternatively with Composer. I will use the latter for this tutorial.

Step 1 – Install HTML2PDF

Use Composer to install the package with the following command

composer require spipu/html2pdf

Step 2 – Require the package in your code

use Spipu\Html2Pdf\Html2Pdf;

Step 3 – Convert inline HTML to PDF

Add the following code to your function or similar. Notice there are two output lines, one of which is commented out, you can add the ‘D’ parameter to force the download immediately, but for this example, I’ve instructed the PDF to load in the browser first.

$html2pdf = new Html2Pdf();
$html2pdf->writeHTML('<h1 style="color:pink;">CodeWall PDF</h1> <br/> <p>Convert this HTML to PDF please!</p>');
$html2pdf->output('myPdf.pdf); // Generate and load the PDF in the browser.

// $html2pdf->output('myPdf.pdf, 'D'); // Generate the PDF execution and force download immediately.

Step 4 – Load the page with the conversion script

Now, you will notice that html2pdf’s output function will essentially instruct the PHP engine/browser to load a PDF page. Which is viewable in a browser like Chrome and is downloadable.

Check out the screenshot below –

html2pdf output screenshot

Summary

HTML2PDF is by no means the only package that can convert HTML to PDF files. This package though is extremely simple to use and it has a good documentation base too. You can check out the docs here.

Be sure to check out the parameter options for the output() function which gives you a flexible variation of functionality including downloading the file to your local computer.

Posted in PHP

Leave a Reply