How to Generate PDFs from Web Pages Using DomPDF

How_to_Generate_PDFs_from_Web_Pages_Using_DomPDF_-_Thumbnail.png

DomPDF is a powerful PHP library for generating PDF documents directly from HTML content. Integrating DomPDF with your web application or website allows you to dynamically create downloadable PDFs from your webpages. Whether you’re generating invoices, product sheets, detailed reports, or other types of documentation, DomPDF efficiently handles HTML to PDF conversion, providing professional and shareable documents.

Benefits of Dynamic PDF Generation

Converting webpages to PDFs dynamically offers:

  • Professional document sharing
  • Easy offline access
  • Consistent document formatting
  • Ideal for invoicing, reports, product sheets, vehicle listings

Prerequisites and Setup

Install DomPDF using Composer:

composer require dompdf/dompdf

Verify DomPDF is active with this snippet:

if (!class_exists('\Dompdf\Dompdf')) {
    echo '<div class="notice notice-error"><p><strong>DomPDF is not loaded.</strong> Please install and activate DomPDF to generate PDFs.</p></div>';
    return;
}

Creating a Custom PDF Template for Print-Friendly HTML

To generate PDF documents effectively, you’ll typically need to create a specialized, print-friendly version of your webpage’s HTML. You can achieve this by passing a URL parameter (?print=1) that triggers loading of this custom HTML template specifically optimized for PDF rendering.

if (isset($_GET['print']) && $_GET['print'] == 1) {
    include('templates/pdf-friendly-template.php'); // Custom PDF-friendly template
    exit();
}

This method allows you to:

  • Simplify the page structure
  • Optimize typography and readability
  • Reduce unnecessary web elements unsuitable for PDF formatting

Building the DomPDF Generation Function

Here is a generic PHP function to generate PDFs dynamically:

function generate_pdf_from_webpage() {
    if (!class_exists('\Dompdf\Dompdf')) {
        echo '<div class="notice notice-error"><p><strong>DomPDF is not loaded.</strong> Please activate it to generate PDFs.</p></div>';
        return;
    }

    if (isset($_POST['pdf_url']) && isset($_POST['pdf_name'])) {
        $page_url = filter_var($_POST['pdf_url'], FILTER_SANITIZE_URL);
        $html_url = $page_url . '?print=1';

        $filename = preg_replace('/[^a-zA-Z0-9-_\.]/', '_', $_POST['pdf_name']);

        $html = file_get_contents($html_url);

        if (!$html) {
            error_log('Failed to fetch HTML from: ' . $html_url);
            return;
        }

        $options = new \Dompdf\Options();
        $options->set('defaultPaperSize', 'A4');
        $options->set('defaultPaperOrientation', 'portrait');
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);

        $dompdf = new \Dompdf\Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename=' . $filename);
        echo $dompdf->output();
        exit;
    }
}

add_action('admin_post_generate_pdf_from_webpage', 'generate_pdf_from_webpage');
add_action('admin_post_nopriv_generate_pdf_from_webpage', 'generate_pdf_from_webpage');

DomPDF Configuration Options

Customize DomPDF settings:

  • Paper Size: ‘A4’, ‘Letter’, ‘Legal’
  • Orientation: ‘portrait’, ‘landscape’
  • HTML5 Parsing: Improves HTML/CSS accuracy
  • Remote Content: Enable to fetch external resources safely

Example configuration:

$options->set('isRemoteEnabled', true);

Creating the PDF Download Button

Add a form button to trigger PDF downloads:

<form method="post" action="/path-to-your-pdf-script">
    <input type="hidden" name="pdf_url" value="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
    <input type="hidden" name="pdf_name" value="document-details.pdf">
    <button type="submit" class="button">Download as PDF</button>
</form>

Customize this button’s appearance using CSS.

Styling PDFs with CSS

Use print-specific CSS for:

  • Page breaks (page-break-before)
  • PDF headers/footers
  • Optimizing image quality

Example CSS snippet:

@media print {
    img { max-width: 100%; height: auto; }
    .no-print { display: none; }
}

Advanced DomPDF Customizations

Customize headers, footers, page numbers, watermarks:

$canvas = $dompdf->getCanvas();
$canvas->page_text(72, 18, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0,0,0));

Security Best Practices

Secure PDF generation:

  • Always sanitize inputs
  • Restrict access using user authentication
  • Validate URLs strictly

Troubleshooting Common DomPDF Issues

Common solutions:

  • Memory issues: Increase PHP memory limit
  • CSS problems: Use simpler CSS rules
  • Complex layouts: Simplify structures or use absolute positioning

Performance Optimization

  • Caching: Store PDFs for repeated use
  • Server optimization: Adjust PHP settings for large document handling

Conclusion

Using DomPDF simplifies creating professional PDFs dynamically. Start generating PDFs for invoices, product sheets, reports, and documentation, enhancing your application’s functionality

FAQs

What kind of CSS does DomPDF support?

DomPDF handles most basic CSS and some advanced properties, but struggles with Flexbox, Grid, and modern layout features. Stick to block layouts and inline styles for best results.

Can I load remote images and fonts?

Yes—enable it via $options->set('isRemoteEnabled', true);. Make sure the URLs are accessible (not behind login walls).

Does it work in shared hosting?

Absolutely. As long as you can run Composer and have enough memory (128MB+), DomPDF works fine on shared servers.

How do I generate a PDF from a specific template?

Create a ?print=1 version of the page and point DomPDF to that URL. Keep it clean, styled for print, and avoid unnecessary JS or AJAX calls.

Can DomPDF handle large documents?

It can, but with caveats. Optimise images, keep layout simple, and increase memory limits if needed. For huge PDFs, consider splitting into sections or using background jobs.