HTML to PDF Conversion in PHP Using dompdf

Listen to this Post

Featured Image
The dompdf library is a powerful tool for converting HTML documents to PDF in PHP. It’s widely used for generating invoices, reports, and other printable documents dynamically. Below is a detailed guide on how to use it effectively.

Installation

First, install dompdf via Composer:

composer require dompdf/dompdf

Basic Usage

Here’s a simple PHP script to convert HTML to PDF:

<?php
require 'vendor/autoload.php';
use Dompdf\Dompdf;

$dompdf = new Dompdf();
$html = '<h1>Hello, PDF!</h1><p>This is a test document.</p>';
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("document.pdf", ["Attachment" => false]);
?>

Advanced Features