Learn how to generate PDF's from HTML data using the Dompdf library in your Symfony 4 project.

How to create a PDF from HTML in Symfony 4 using Dompdf

The generation of PDF files is a must nowadays on any application. Although there are a lot of libraries that allow you to generate PDFs from HTML in PHP, dompdf is without a doubt one of the favorites libraries of the developers due to its simplicity and effectiveness during the creation of PDFs with this language.

Dompdf is a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is a style-driven renderer: it will download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes.

In this article, we'll show you how to generate a PDF file from HTML using the Dompdf library in your Symfony 4 based project.

Requirements

In this tutorial, we'll use the traditional web application version of Symfony 4 that includes Twig, Doctrine etc. We'll write examples based in symfony controllers and to generate the PDFs. Our example HTML will be stored in a Twig file at /project/templates/default/mypdf.html.twig and contains the following HTML that will be shown as PDF:

{# ./templates/default/mypdf.html.twig #}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Title of the PDF</title>
    </head>
    <body>
        <h4>{{ title }}</h4>
        <p>Lorem Ipsum</p>
    </body>
</html>

We'll send a variable namely title from the controller. Knowing this, let's get started !

1. Install Dompdf

The preferred way to handle dependencies in Symfony 4 is via Composer. There's a dompdf package available in the packagist site. You can install the Dompdf library in your Symfony project with the following command:

composer require dompdf/dompdf

After the installation, you will be able to use the library and its namespaces. For more information about this library, please visit their official repository at Github here or the official website here.

2. Create PDF files by doing

As a developer, you will learn by doing and that means, write and run some code ! We'll show you a couple of traditional examples that you will need often, this cases are the creation of a PDF file in the disk (Saving a excel file in a path) and a streamed response (an inline disposition file to see the PDF in the browser) or forcing the download of the pdf file (attachment):

A. Generate and force PDF File download

If you are willing to create the PDF file and serve it as file, so the user can download it, you won't need to write it to the disk. You can instead, stream the response:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

// Include Dompdf required namespaces
use Dompdf\Dompdf;
use Dompdf\Options;

class DefaultController extends Controller
{
    public function index()
    {
        // Configure Dompdf according to your needs
        $pdfOptions = new Options();
        $pdfOptions->set('defaultFont', 'Arial');
        
        // Instantiate Dompdf with our options
        $dompdf = new Dompdf($pdfOptions);
        
        // Retrieve the HTML generated in our twig file
        $html = $this->renderView('default/mypdf.html.twig', [
            'title' => "Welcome to our PDF Test"
        ]);
        
        // Load HTML to Dompdf
        $dompdf->loadHtml($html);
        
        // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Output the generated PDF to Browser (force download)
        $dompdf->stream("mypdf.pdf", [
            "Attachment" => true
        ]);
    }
}

B. Generate and view PDF in the browser

If you want to directly see the generated PDF in the browser, just set the attachment option to false during the stream:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

// Include Dompdf required namespaces
use Dompdf\Dompdf;
use Dompdf\Options;

class DefaultController extends Controller
{
    public function index()
    {
        // Configure Dompdf according to your needs
        $pdfOptions = new Options();
        $pdfOptions->set('defaultFont', 'Arial');
        
        // Instantiate Dompdf with our options
        $dompdf = new Dompdf($pdfOptions);
        
        // Retrieve the HTML generated in our twig file
        $html = $this->renderView('default/mypdf.html.twig', [
            'title' => "Welcome to our PDF Test"
        ]);
        
        // Load HTML to Dompdf
        $dompdf->loadHtml($html);
        
        // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Output the generated PDF to Browser (inline view)
        $dompdf->stream("mypdf.pdf", [
            "Attachment" => false
        ]);
    }
}

C. Generate and store PDF in the disk

If you want to save the PDF in your storage, just retrieve the binary data of the PDF and save it into a file, you can do it using file_put_contents:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

// Include Dompdf required namespaces
use Dompdf\Dompdf;
use Dompdf\Options;

class DefaultController extends Controller
{
    public function index()
    {
        // Configure Dompdf according to your needs
        $pdfOptions = new Options();
        $pdfOptions->set('defaultFont', 'Arial');
        
        // Instantiate Dompdf with our options
        $dompdf = new Dompdf($pdfOptions);
        
        // Retrieve the HTML generated in our twig file
        $html = $this->renderView('default/mypdf.html.twig', [
            'title' => "Welcome to our PDF Test"
        ]);
        
        // Load HTML to Dompdf
        $dompdf->loadHtml($html);
        
        // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();

        // Store PDF Binary Data
        $output = $dompdf->output();
        
        // In this case, we want to write the file in the public directory
        $publicDirectory = $this->get('kernel')->getProjectDir() . '/public';
        // e.g /var/www/project/public/mypdf.pdf
        $pdfFilepath =  $publicDirectory . '/mypdf.pdf';
        
        // Write file to the desired path
        file_put_contents($pdfFilepath, $output);
        
        // Send some text response
        return new Response("The PDF file has been succesfully generated !");
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors