pdf libraries

pdf libraries

PHP

PHP

How to Generate PDF from HTML Using Dompdf

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Oct 15, 2024

Oct 15, 2024

Introduction to Dompdf: Converting HTML to PDF in PHP

Dompdf is an open-source HTML to PDF converter written in PHP. It enables developers to transform HTML and CSS content into PDF files with minimal effort. Unlike other PHP PDF libraries that require manual assembly of PDF elements, Dompdf allows you to design PDFs using standard HTML and CSS, making the development process more intuitive and efficient.

You can access the full documentation for dompdf here.

Comparison Between Dompdf and Other PHP PDF Libraries

Print from the packagist

While several PHP PDF libraries are available, Dompdf stands out for its simplicity and ease of use, with a total of 111.6 million installs. Libraries like TCPDF (69.2 million installs) and MPDF (53 million installs) require you to build PDFs programmatically, which can be time-consuming for complex documents.

Dompdf, however, interprets HTML and CSS directly, allowing you to leverage existing web design skills and resources. It also supports a broad range of CSS properties, giving you greater control over the styling of your PDFs.

Guide to generate pdf from html using php dompdft
Guide to generate pdf from html using php dompdft

Setting Up Dompdf in Your PHP Project

Integrating Dompdf into your project is straightforward, especially when using Composer for dependency management.

Installing Dompdf via Composer Step-by-Step

1. Install Composer: If you haven’t already, download and install Composer from getcomposer.org.

2. Require Dompdf: In your project directory, run the following command:

3. Include the Autoloader: Add the Composer autoloader to your PHP script:

Configuring Dompdf for HTML to PDF Conversion

Initialize Dompdf in your script:



Set the paper size and orientation (optional):

Exploring the Dompdf API Essentials

Load your HTML content:

$html = '<h1>Invoice</h1><p>This is your invoice.</p>

Render the PDF:

Output the generated PDF to the browser:

Generating PDFs from HTML with Dompdf

Creating visually appealing PDFs involves preparing your HTML content meticulously and incorporating dynamic data effectively.

Preparing HTML Content for Accurate PDF Rendering

Design a comprehensive HTML invoice template that reflects the structure of your desired PDF:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <style>
        body {
            font-family: DejaVu Sans, sans-serif;
            margin: 0;
            padding: 20px;
        }
        .invoice-box {
            max-width: 800px;
            margin: auto;
            border: 1px solid #eee;
            padding: 30px;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .information {
            margin-bottom: 40px;
        }
        .information .company-details,
        .information .customer-details {
            width: 45%;
            display: inline-block;
            vertical-align: top;
        }
        .information .company-details {
            float: left;
        }
        .information .customer-details {
            float: right;
            text-align: right;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 40px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        table th, table td {
            padding: 12px;
            text-align: left;
        }
        .total {
            text-align: right;
            margin-right: 20px;
        }
    </style>
</head>
<body>
    <div class="invoice-box">
        <h1>Invoice</h1>
        <div class="information">
            <div class="company-details">
                <strong>Company Name</strong><br>
                12345 Sunny Road<br>
                Sunnyville, TX 12345
            </div>
            <div class="customer-details">
                <strong><?php echo htmlspecialchars($customerName); ?></strong><br>
                <?php echo htmlspecialchars($customerAddress); ?><br>
                <?php echo htmlspecialchars($customerCity); ?>
            </div>
            <div style="clear: both;"></div>
        </div>
        <p>Date: <?php echo htmlspecialchars($invoiceDate); ?></p>
        <table>
            <tr>
                <th>Item</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
            </tr>
            <?php foreach($items as $item): ?>
            <tr>
                <td><?php echo htmlspecialchars($item['item']); ?></td>
                <td><?php echo htmlspecialchars($item['description']); ?></td>
                <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                <td>$<?php echo number_format($item['price'], 2); ?></td>
                <td>$<?php echo number_format($item['quantity'] * $item['price'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <div class="total">
            <strong>Total Due: $<?php echo number_format($totalDue, 2); ?></strong>
        </div>
    </div>
</body>
</html>

In this example, dynamic content such as the customer’s name, address, invoice date, the list of items, and the total due are integrated using PHP variables within the HTML. This allows you to generate personalized invoices for each customer.

Sample PHP Variables:

<?php
$customerName = 'John Doe';
$customerAddress = '54321 Cloudy Road';
$customerCity = 'Cloudsville, CA 54321';
$invoiceDate = date('F d, Y');
$items = [
    [
        'item' => '001',
        'description' => 'Web Design Services',
        'quantity' => 1,
        'price' => 1500.00
    ],
    [
        'item' => '002',
        'description' => 'Hosting (12 months)',
        'quantity' => 1,
        'price' => 240.00
    ],
    [
        'item' => '003',
        'description' => 'Domain Registration (1 year)',
        'quantity' => 1,
        'price' => 15.00
    ],
];
$totalDue = array_reduce($items, function($sum, $item) {
    return $sum + ($item['quantity'] * $item['price']);
}, 0);

By embedding PHP code, you can generate dynamic invoices with varying data for different customers.

Embedding Images and Fonts in Your PDFs

To embed images, such as a company logo, use absolute paths or encode images using base64:

<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents('path/to/logo.png')); ?>" alt="Company Logo">

Ensure that the image path is correct and accessible to the script.

Handling Pagination and Dynamic Content

Dompdf handles pagination automatically, but you can add page numbers and headers/footers for a professional touch:

<div style="position: fixed; bottom: 0; width: 100%; text-align: center;">
    Page {PAGE_NUM} of {PAGE_COUNT}
</div>

Include this snippet in your HTML to display page numbers on each page.

Using Third-Party PDF APIs for Scale

As your application scales, you might face performance challenges with server-side PDF generation. In such cases, consider using third-party PDF APIs like pdforge. These services handle PDF rendering externally, reducing server load and offering additional features like concurrent processing and advanced formatting.

To integrate the PDForge API:

1. Sign Up: Register for an account at pdforge.com.

2. API Key: Obtain your API key from the dashboard.

3. API Calls: Modify your code to send HTML content to the API endpoint:



Replace 'your-template' with your actual template ID and 'your-api-key' with your API key. This method offloads PDF generation to pdforge, allowing for better scalability.

Conclusion

Leveraging Dompdf enables efficient and elegant PDF generation from HTML in PHP, making it an excellent choice for developers implementing PDF reports in their SaaS applications. Its ease of use and compatibility with HTML and CSS make it ideal for small to medium-sized projects.

However, when dealing with large-scale applications or requiring advanced features, consider other options. Libraries like TCPDF offer more control, while third-party PDF APIs like pdforge provide scalability and reduce server overhead. Selecting the right tool depends on your project’s specific needs, performance requirements, and resource constraints.

Generating pdfs at scale can be quite complicated!

Generating pdfs at scale can be quite complicated!

We take care of all of this, so you focus on what trully matters on your Product!

We take care of all of this, so you focus on what trully matters on your Product!

Try for free

7-day free trial

Table of contents

Title