How to Convert HTML to PDF in PHP Using MPDF

How to Convert HTML to PDF in PHP Using MPDF

Introduction

Generating PDF files from HTML content is essential for invoices, reports, contracts, and printable documents. MPDF is a powerful PHP library that allows us to convert HTML content—including CSS styles, images, and tables—into high-quality PDFs.

With MPDF, you can:

Convert HTML pages into PDF dynamically
Use CSS styling to format PDFs
Include images, tables, and custom fonts
Save, download, or email generated PDFs

By the end of this guide, you’ll be able to generate professional PDFs from HTML in PHP. 🚀

1. Installing MPDF in PHP

MPDF can be installed via Composer (recommended) or manually.

Install via Composer

composer require mpdf/mpdf

Include MPDF in Your PHP Script

require 'vendor/autoload.php';

use Mpdf\Mpdf;

Now, MPDF is ready to generate PDFs from HTML!

2. Creating a Simple PDF from HTML

Let's generate a basic PDF with plain HTML content.

Example: Convert Simple HTML to PDF

require 'vendor/autoload.php';

use Mpdf\Mpdf;

$mpdf = new Mpdf();
$html = '<h1>Hello, MPDF!</h1><p>This is a simple PDF generated from HTML.</p>';

$mpdf->WriteHTML($html);
$mpdf->Output('simple.pdf', 'I');

Explanation:

WriteHTML($html) – Converts HTML into a PDF.
Output('simple.pdf', 'I') – Displays the PDF in the browser.

🔹 Change 'I' to 'D' to force a download:

$mpdf->Output('download.pdf', 'D');

3. Converting an External HTML File to PDF

Instead of embedding HTML, load it from an external file (e.g., invoice.html).

$html = file_get_contents('invoice.html');

$mpdf = new Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output('invoice.pdf', 'I');

Works well for exporting webpages as PDFs.

4. Styling PDF with CSS (Tables, Fonts, Colors)

MPDF fully supports CSS, allowing us to format the document.

Example: Styled Invoice with CSS

$html = '
<style>
  body { font-family: Arial, sans-serif; }
  h1 { color: #333; text-align: center; }
  table { width: 100%; border-collapse: collapse; margin-top: 20px; }
  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  th { background-color: #f4f4f4; }
</style>

<h1>Invoice</h1>
<table>
  <tr><th>Item</th><th>Quantity</th><th>Price</th></tr>
  <tr><td>Product A</td><td>1</td><td>$100</td></tr>
  <tr><td>Product B</td><td>2</td><td>$50</td></tr>
</table>
';

$mpdf = new Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output('styled_invoice.pdf', 'I');

Tables, fonts, and colors work just like in HTML & CSS.

🔹 Use @page CSS rules for custom margins and headers.

5. Adding Images to PDF

MPDF allows embedding logos, product images, and charts in PDFs.

Example: Add an Image to PDF

$html = '
<h1>Company Report</h1>
<img src="logo.png" width="150">
<p>Annual Performance Overview.</p>
';

$mpdf = new Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output('image_pdf.pdf', 'I');

Supports PNG, JPEG, GIF, and SVG images.

🔹 Use full URLs (https://example.com/image.jpg) for external images.

6. Saving PDFs to the Server

To store generated PDFs, use file_put_contents().

$pdfOutput = $mpdf->Output('', 'S'); // Get PDF content as a string
file_put_contents('saved_pdfs/invoice.pdf', $pdfOutput);

Useful for storing and processing PDFs later.

7. Emailing a PDF as an Attachment

MPDF works well with PHPMailer for emailing PDFs.

Example: Email a PDF Attachment

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();
$mail->addAttachment('saved_pdfs/invoice.pdf');
$mail->send();

echo "PDF sent via email!";

Automatically generates and emails PDF documents.

8. Adding Page Numbers and Headers

For multi-page PDFs, add headers, footers, and page numbers dynamically.

Example: Add Page Numbers to a PDF

$mpdf = new Mpdf();
$mpdf->SetFooter('Page {PAGENO} of {nbpg}');

$html = '<h1>Multi-Page Report</h1><p>Report content goes here...</p>';
$mpdf->WriteHTML($html);

$mpdf->Output('paged_report.pdf', 'I');

Ensures professional document formatting.

9. Securing PDFs (Password Protection and Encryption)

To protect a PDF, apply a password and restrict permissions.

Example: Password-Protect a PDF

$mpdf->SetProtection(['copy', 'print'], 'userpassword', 'adminpassword');
$mpdf->Output('secure.pdf', 'I');

Users must enter a password to open or print the PDF.

10. Converting Dynamic Web Pages to PDF

Capture dynamic webpage content and save it as a PDF.

Example: Convert a Live Webpage to PDF

$html = file_get_contents("https://example.com/report");
$mpdf->WriteHTML($html);
$mpdf->Output('webpage.pdf', 'I');

Great for exporting reports, dashboards, and blog posts.

Best Practices for HTML to PDF Conversion in PHP

Use inline CSS for best PDF rendering compatibility.
Optimize images before adding them to PDFs.
Use file_put_contents() to store PDFs on the server.
Test PDF output on different devices and screen sizes.
Secure sensitive PDFs with password protection.

Conclusion

With MPDF, you can easily convert HTML pages, invoices, reports, and receipts into PDF format while maintaining CSS styling, images, and tables.

MPDF simplifies HTML-to-PDF conversion in PHP.
Supports styling, images, tables, and dynamic content.
Great for generating invoices, reports, and order receipts.

By following this guide, you can efficiently generate and process PDFs from HTML in your PHP applications! 🚀

Leave a Reply