How to Convert HTML to PDF in PHP

Often you may need to convert HTML to PDF using PHP, on your website or application. While PHP does not provide this feature out of box, there are many third-party libraries to convert HTML to PDF. In this article, we will look at how to convert HTML to PDF in PHP using HTML2PDF library. It is open source, free and also supports CSS styling in your HTML to PDF conversion.


How to Convert HTML to PDF in PHP

Here are the steps to convert HTML to PDF in PHP using HTML2PDF. Please note, it works on PHP 5.6 to 7.4.


1. Install HTML2PDF

You may install HTML2PDF from its GitHub Repository or using composer. We will use composer utility for our example. Open terminal/command prompt and run the following command to install HTML2PDF.

$ composer require spipu/html2pdf


2. Require HTML2PDF

Add the following line to the php file that handles pdf export. It will import HTML2PDF library and make it available in that file.

use Spipu\Html2Pdf\Html2Pdf;


3. Convert HTML to PDF

Add the following lines in the PHP function/event handler/request handler you have created to convert HTML to PDF.

$html2pdf = new Html2Pdf();
$html2pdf->writeHTML('<h1 style="color:pink;">Hello World 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.

Let us look at the above code line by line.

First, we create an instance of Html2Pdf. Then we input our HTML to it using writeHTML function. Finally, we export the output as PDF using output function.

Please note, the above code will convert HTML to PDF and open it in web browser. If you want to force user to download then add ‘D’ option, as shown in the 4th line, which has been commented. You may pass the HTML code via a variable, instead doing inline conversion as we have done.

In our case, the PHP will load the PDF in web browser.

There are many other third-party libraries such as DOMPDF to convert HTML to PDF. However, HTML2PDF is easy to use and free, and has good documentation. Here is the link to documentation of HTML2PDF.

Typically, the export to pdf functionality is required in many websites and applications and is often embedded into large functions that perform more tasks. We have provided a simple example that you can easily modify and add into your existing codebase.

Also read:

How to Find Inode Number of File in Linux
How to Create Ext4 Filesystem in Linux
How to Increase Inode Limit in Linux
How to Enable HAProxy Stats
How to Convert DEB to RPM in Linux

Leave a Reply

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