pdf libraries

pdf libraries

PHP

PHP

How to Generate PDF from HTML Using mPDF

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Oct 17, 2024

Oct 17, 2024

Introduction to mPDF: Converting HTML to PDF in PHP

You can generate PDF from HTML using mPDF, an open-source PHP library that interprets HTML code and stylesheets to render PDFs closely mirroring your original web content. Converting HTML content into PDF format is a common requirement for many SaaS applications, especially when generating reports, invoices, or documentation. In this article, we’ll delve into how you can seamlessly transform HTML to PDF using mPDF, a powerful tool designed for this exact purpose.

You can check out the full documentation here.

Comparison Between TCPDF and Other PHP PDF Libraries

The Packagist print for mpdf

When it comes to PHP PDF libraries, options like TCPDF (69.2 million installs), Dompdf (111.6 million installs) and FPDF (1.6 million installs) often come to mind. Here’s how mPDF stands out:

Ease of Use: mPDF simplifies the conversion process by directly using HTML and CSS, reducing the learning curve.

Feature-Rich: Supports advanced CSS styling, including floats, positioned elements, and even CSS3 properties.

Unicode Support: Excellent support for Unicode languages, making it ideal for multilingual applications.

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

Setting Up mPDF in Your PHP Environment

Installing mPDF: Quick Start Guide for Developers

To get started with mPDF, install it via Composer:

Alternatively, download it directly from the mPDF GitHub repository.

Configuring mPDF for Seamless HTML to PDF Transformation

After installation, include the mPDF autoloader in your PHP script:



Configure options during initialization, such as page size, orientation, and margins:



Converting HTML to PDF Using mPDF

Preparing Your HTML Content for mPDF Conversion

Let’s create a full invoice example. First, design your HTML template (invoice_template.php):

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: sans-serif; }
        h1 { color: #333; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 8px 12px; border: 1px solid #ddd; }
        th { background-color: #f4f4f4; text-align: left; }
        .total { font-weight: bold; }
        .right { text-align: right; }
    </style>
</head>
<body>
    <h1>Invoice #<?php echo $invoiceNumber; ?></h1>
    <p>Date: <?php echo date('Y-m-d'); ?></p>
    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th class="right">Quantity</th>
                <th class="right">Price</th>
                <th class="right">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($items as $item): ?>
            <tr>
                <td><?php echo htmlspecialchars($item['description']); ?></td>
                <td class="right"><?php echo intval($item['quantity']); ?></td>
                <td class="right"><?php echo number_format($item['price'], 2); ?></td>
                <td class="right"><?php echo number_format($item['quantity'] * $item['price'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
            <tr>
                <td colspan="3" class="right total">Total Amount:</td>
                <td class="right total"><?php echo number_format($totalAmount, 2); ?></td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Next, in your PHP script, populate the variables and render the HTML:



This script generates a PDF invoice based on the HTML template, complete with styling and dynamic content.

Styling PDFs: How mPDF Handles CSS and Media Files

mPDF supports inline CSS and external stylesheets. You can link external CSS files if needed:

<link rel="stylesheet" href="styles.css">

For media files like images, ensure paths are correct or use absolute URLs. mPDF can embed images from local files or URLs:

<img src="logo.png" alt="Company Logo" style="width:150px;">

Ensure images are accessible to the script and consider using base64 encoding for embedding images directly.

Leveraging mPDF’s PDF API for Custom Functionality

Utilize mPDF’s API to add custom features:

Watermarks:



Headers and Footers:

$mpdf->SetHTMLHeader('<div style="text-align: right;">Invoice #'.$invoiceNumber.'</div>');
$mpdf->SetHTMLFooter('<div style="text-align: center;">{PAGENO}</div>

Password Protection:

Implementing Security: Encrypting and Protecting PDFs

Secure your PDFs by setting permissions and passwords:



This ensures only authorized users can view or modify the PDF.

Troubleshooting Common mPDF Issues in PHP Projects

Memory Limit Errors: Increase PHP’s memory limit or optimize your HTML content.

Missing Fonts: Ensure required fonts are installed and accessible to mPDF. You can specify a font directory:



Incorrect Image Paths: Use absolute paths or adjust img_dpi setting if images appear distorted.

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

mPDF is an excellent choice for generating PDFs from HTML in PHP applications, offering a balance of simplicity and powerful features. It’s ideal for small to medium-scale projects where server resources are sufficient. However, for large-scale applications requiring high concurrency and additional features, consider using third-party PDF APIs like pdforge.

When choosing between mPDF and other alternatives:

Use mPDF when you need tight integration with PHP and control over the PDF generation process.

Consider Other Libraries like TCPDF or Dompdf if they better suit your project’s requirements.

Opt for Third-Party PDF Generation APIs when you need scalability, reliability, and advanced features without managing the underlying infrastructure.

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