Converting HTML to PDF in PHP Using DomPDF

Converting HTML to PDF in PHP Using DomPDF

Introduction

Converting HTML to PDF is essential for invoices, reports, order receipts, certificates, and downloadable documents. Instead of manually creating PDFs, DomPDF allows you to generate PDFs directly from HTML and CSS, preserving styling and formatting.

With DomPDF, you can:

Convert web pages to PDF dynamically
Use HTML & CSS for PDF layout and styling
Add images, tables, and custom fonts to PDFs
Save, download, or email generated PDFs

In this guide, we’ll cover installing DomPDF, converting HTML to PDF, and advanced styling techniques for creating professional-looking documents.

1. Installing DomPDF in PHP

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

Install via Composer (Recommended)

composer require dompdf/dompdf

After installation, include DomPDF in your PHP file:

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

Manual Installation

  1. Download DomPDF from GitHub.
  2. Extract and place the dompdf folder in your project.
  3. Include DomPDF in your script:
require 'dompdf/autoload.php';
use Dompdf\Dompdf;

DomPDF is now ready for use!

2. Converting Simple HTML to PDF

Let’s start with a basic example that converts plain HTML into a PDF.

Example: Convert HTML to PDF in PHP

require 'vendor/autoload.php';

use Dompdf\Dompdf;

$html = '<h1>Invoice</h1><p>This is a generated PDF from HTML!</p>';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("document.pdf", ["Attachment" => false]); // Opens in browser

Explanation:

loadHtml($html) – Loads the HTML content.
setPaper('A4', 'portrait') – Sets PDF size & orientation.
render() – Converts HTML to a PDF format.
stream("document.pdf", ["Attachment" => false]) – Opens PDF in browser (set "Attachment" => true for download).

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');

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("invoice.pdf", ["Attachment" => true]); // Forces download

Useful for exporting entire web pages as PDFs.

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

DomPDF supports CSS for styling PDFs, including custom fonts, colors, and layouts.

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>
';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("styled_invoice.pdf", ["Attachment" => false]);

Tables, fonts, and colors are fully supported in DomPDF.
Use @page CSS rules for custom margins and headers.

5. Adding Images to PDFs in DomPDF

You can embed logos, charts, or product images into the PDF.

Example: Adding an Image

$html = '
<h1>Company Report</h1>
<img src="logo.png" width="150">
<p>Company performance for the year.</p>
';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("image_pdf.pdf", ["Attachment" => false]);

Best Practices for Image Handling:

Use full URLs (https://example.com/image.jpg) for external images.
For local images, use base64_encode() to embed them.

6. Saving PDF Files to Server

To store generated PDFs on the server, use file_put_contents().

$pdfOutput = $dompdf->output();
file_put_contents('invoices/invoice.pdf', $pdfOutput);

Now, the PDF is saved and can be retrieved later.

7. Sending PDF as Email Attachment

To email the generated PDF, integrate with PHPMailer.

use PHPMailer\PHPMailer\PHPMailer;

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

Automatically attach PDFs for invoice emails or reports.

8. Handling Large PDFs (Performance Optimization)

Optimize DomPDF Performance for Large PDFs:

Use inline CSS instead of external stylesheets.
Convert large images to WebP or optimize PNGs.
Set a higher memory limit in PHP (ini_set('memory_limit', '256M');).
Use setPaper('A4', 'portrait') to prevent default resizing.

9. Converting Dynamic Web Pages to PDF

To capture an entire webpage as PDF, use file_get_contents() with DomPDF.

$html = file_get_contents("https://example.com/report");
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream("webpage.pdf", ["Attachment" => false]);

Works 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 screen sizes and orientations.

Conclusion

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

DomPDF 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 PDFs from HTML in your PHP applications. 🚀

Leave a Reply