Convert HTML to PDF in PHP with Dompdf

PDF is a file format created by Adobe Systems for illustrating text and images in a fixed-layout document. PDF is used to download a bunch of data or text content in the web application. The PDF file format is the perfect choice to download text or HTML content in a file. At the time of downloading web page content as a PDF file, it requires converting HTML to PDF. In this tutorial, we will show you how to convert HTML to PDF and generate PDF files using PHP.

Dompdf is a PHP library that provides a simple way to convert HTML to PDF documents. Using the Dompdf library you can easily generate PDF from the HTML page in PHP. The example code will help you to implement PDF generation functionality in the web application and make it simple to convert HTML to PDF in PHP with Dompdf.

Dompdf Installation and Setup

Before getting started, download stable release of the Dompdf library and include it in the project directory.

Note that: You don’t need to download the Dompdf library separately, all the required files are included in our source code package.

Instantiate Dompdf Class

To use the Dompdf class, you need to include the autoloader in the PHP script. Use the following PHP code to instantiate and use the dompdf class.

// Include autoloader 
require_once 'dompdf/autoload.inc.php';

// Reference the Dompdf namespace
use Dompdf\Dompdf;

// Instantiate and use the dompdf class
$dompdf = new Dompdf();

Basic Usage (Convert HTML to PDF)

The following example shows how to use Dompdf to convert HTML and generate PDF with minimal configuration.

// Load HTML content 
$dompdf->loadHtml('

Welcome to CodexWorld.com

'
);

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

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

// Output the generated PDF to Browser
$dompdf->stream();

Advanced Usage

With the Dompdf library, you can easily enhance the functionality of PDF creation. The following code generates PDF from an HTML file ( pdf-content.html ).