DEV Community

Alpha Olomi
Alpha Olomi

Posted on

Generating PDF documents in Laravel

Laravel and DomPDF: Step by step guide to generating PDF Documents with Images and CSS

Creating PDF documents is a common requirement in web applications, especially for generating invoices, receipts, certificates, tickets, and various reports. In this comprehensive tutorial, we'll delve into using Laravel and DomPDF to generate PDF documents with images and CSS. We'll cover configuration options, design considerations, output size, performance, and database queries. Additionally, we'll discuss tips and tricks for handling page breaks, loading images using base64, and more.

Prerequisites

Before we start, ensure you have the following installed:

  • PHP >=8.2
  • Composer 2+
  • Laravel 10+

Introduction

DomPDF is a popular PHP library that allows you to generate PDF documents from HTML content. It supports CSS styling, images, and various configuration options. By integrating DomPDF with Laravel, you can easily create sophisticated PDF documents using Blade templates and Laravel's powerful features.

Other popular PDF libraries include TCPDF, FPDF, and Snappy.

However, DomPDF is widely used due to its ease of integration and robust feature set.

In this tutorial, we'll walk through the process of setting up a Laravel project, configuring DomPDF, creating a controller to handle PDF generation, designing a Blade template for the PDF content, adding routes, and optimizing performance. We'll also discuss advanced configuration options and provide tips and tricks for generating high-quality PDF documents.

Assumptions

This tutorial assumes you have a basic understanding of Laravel and PHP. If you're new to Laravel, consider going through the official Laravel documentation to familiarize yourself with the framework. Other wise you can follow the Laravel Bootcamp to get started with Laravel.

Step 1: Setting Up Laravel Project

First, create a new Laravel project if you don't already have one, or use an existing project, Of course, you can skip this step if you already have a Laravel project.

composer create-project --prefer-dist laravel/laravel pdf-tutorial
cd pdf-tutorial
Enter fullscreen mode Exit fullscreen mode

Next, install DomPDF:

composer require barryvdh/laravel-dompdf
Enter fullscreen mode Exit fullscreen mode

Publish the configuration file:

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Step 2: Configuring DomPDF

Open the config/dompdf.php file. The configuration file contains various options for customizing the PDF output. Here you can set various options including the default paper size, orientation, font, and more.

  • Paper size: You can set the default paper size.
  'default_paper_size' => 'a4',
Enter fullscreen mode Exit fullscreen mode
  • Orientation: Set the default orientation (portrait or landscape).
  'orientation' => 'portrait',
Enter fullscreen mode Exit fullscreen mode
  • Font: You can specify the default font and add custom fonts.
  'default_font' => 'serif',
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating a Controller

Create a controller to handle PDF generation:

php artisan make:controller PDFController
Enter fullscreen mode Exit fullscreen mode

In app/Http/Controllers/PDFController.php, add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    public function generatePDF()
    {
        $data = [
            'title' => 'Laravel PDF Example',
            'date' => date('m/d/Y'),
        ];

        $pdf = PDF::loadView('myPDF', $data);

        return $pdf->download('document.pdf');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Creating a Blade Template

Create a Blade template for the PDF content:

touch resources/views/myPDF.blade.php
Enter fullscreen mode Exit fullscreen mode

Add the following content to myPDF.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel PDF Example</title>
    <style>
        body {
            font-family: 'Arial, sans-serif';
        }
        .container {
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .content {
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{ $title }}</h1>
            <p>Date: {{ $date }}</p>
        </div>
        <div class="content">
            <p>This is an example of a PDF document generated using Laravel and DomPDF.</p>
        </div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Adding Routes

Add routes to handle PDF generation in routes/web.php:

use App\Http\Controllers\PDFController;

Route::get('generate-pdf', [PDFController::class, 'generatePDF']);
Enter fullscreen mode Exit fullscreen mode

Step 6: Adding Images

You can add images to the PDF by embedding them as base64-encoded strings or using URLs.

Images can be embedded directly in the Blade template using base64 encoding. For example, to embed an image from the public/images this is how you can do it:

<img src="data:image/png;base64,{{ base64_encode(file_get_contents(public_path('images/logo.png'))) }}" alt="Logo">
Enter fullscreen mode Exit fullscreen mode

Or directly from a URL:

<img src="{{ asset('images/logo.png') }}" alt="Logo">
Enter fullscreen mode Exit fullscreen mode

Step 7: Optimizing Performance

Database Queries

When dealing with large datasets (e.g., 1,000+ records), use pagination or chunking to manage memory usage:

$data = DB::table('users')->paginate(50);

$pdf = PDF::loadView('myPDF', ['data' => $data]);
Enter fullscreen mode Exit fullscreen mode

Output Size

To reduce the output size, minimize the use of heavy images and opt for vector graphics when possible. Also, use efficient CSS.

Page Breaks

Ensure content is well-structured for page breaks. Use CSS to handle page breaks:

.page-break {
    page-break-after: always;
}
Enter fullscreen mode Exit fullscreen mode

And in your Blade template:

<div class="page-break"></div>
Enter fullscreen mode Exit fullscreen mode

Step 8: Advanced Configuration

For more advanced configurations, refer to the DomPDF documentation. You can customize almost everything, from margins to the way fonts are loaded.

Using Custom Fonts

To use custom fonts, first, add them to your project and configure DomPDF to use them:

'custom_font_dir' => base_path('resources/fonts/'),
'custom_font_data' => [
    'custom-font' => [
        'R' => 'CustomFont-Regular.ttf',
        'B' => 'CustomFont-Bold.ttf',
    ]
],
Enter fullscreen mode Exit fullscreen mode

In your Blade template:

<style>
    body {
        font-family: 'custom-font', sans-serif;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following this step-by-step guide, you can generate sophisticated PDF documents using Laravel and DomPDF, complete with images and CSS styling. This tutorial has covered essential configuration options, design considerations, performance optimization. You can expand this foundation to build a robust document generation system for your Laravel application.

Potential Series and Repository

This tutorial is part of a series on PDF generation with Laravel. A complete repository with various document templates (invoices, receipts, certificates, tickets, etc.) can be found here. Feel free to contribute and expand the collection.

Happy coding!

Top comments (3)

Collapse
 
websilvercraft profile image
websilvercraft

Nice, I'm looking for available options to handle a4 pages in html and I discovered it's not that easy. I'm building a resume template in html, and tying to split it in a4 pages on screens is challenging. I'm also looking for other options.

Collapse
 
mp3mba profile image
Godfrey Mpuya

Nice article bro๐Ÿš€๐Ÿš€๐Ÿš€

Collapse
 
rretzko profile image
Rick Retzko

Nice guide for getting everything set up to go.
I'd suggest adding "use Barryvdh\DomePDF\Facade\Pdf" in place of "use PDF" in the controller to reduce a bit of confusion.