Generating PDF from HTML In Symfony 5

Generating PDF from HTML In Symfony 5

Avatar photoPosted by

Good day fellow dev, in this blog I will be showing you how to generate PDF from HTML in Symfony 5. PDF has been one of the most commonly used document format today. Most of the web apps has a functionality that generate a PDF for invoice. receipts, reports and others.

What is PDF? It stands for Portable Document Format. It is a file format developed by Adobe to present or display documents in a manner independent of application software, hardware and operating systems.

What is Symfony? Symfony is a PHP framework used to develop web application, APIs, microservices and web services. Symfony is one of the leading PHP framework for creating websites and web application.

Step 1: Install Symfony 5

First, select a folder that you want Symfony to be installed then execute this command on Terminal or CMD to install:

Install via composer:

composer create-project symfony/website-skeleton symfony-5-pdf

Install via Symfony CLI:

symfony new symfony-5-pdf--full

Step 2: Set Database Configuration

We must configure our database to avoid errors. Open the .env file and set database configuration. We will be using MySQL on this tutorial. Uncomment the DATABASE_URL variable for MySQL and updates its configs. Make sure you commented out the other DATABASE_URL variables.


# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
# Real environment variables win over .env files.
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
###> symfony/framework-bundle ###
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://db_user:db_password@"
###< doctrine/doctrine-bundle ###

Step 3: Install DOMPDF Package

We will then install this package dompdf/dompdf, this package will be used in converting HTML into PDF. Run this comman to install the package:

composer require dompdf/dompdf

Step 4: Create A Controller

We will now create our controller, run this command to create a controller:

 php bin/console make:controller PdfGenerator

After creating a controller add this codes:


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Dompdf\Dompdf;

class PdfGeneratorController extends AbstractController
     * @Route("/pdf/generator", name="pdf_generator")
    public function index(): Response
        $data = [
            'imageSrc'  => $this->imageToBase64($this->getParameter('kernel.project_dir') . '/public/img/profile.png'),
            'name'         => 'John Doe',
            'address'      => 'USA',
            'mobileNumber' => '000000000',
            'email'        => ''
        $html =  $this->renderView('pdf_generator/index.html.twig', $data);
        $dompdf = new Dompdf();
        return new Response (
            $dompdf->stream('resume', ["Attachment" => false]),
            ['Content-Type' => 'application/pdf']

    private function imageToBase64($path) {
        $path = $path;
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        return $base64;

Step 5: Update The View

We will now update the view file that was created when we create a controller. Open the file /templates/pdf_generator/index.html.twig and remove the existing codes and change it into these:


<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <div style="margin: 0 auto;display: block;width: 500px;">
        <table width="100%" border="1">
                <td colspan="2">
                    <img src="{{imageSrc}}" style="width:200px;"> 
                <td>Mobile Number:</td>

Before proceeding to the next step, make sure you have an image file in the /public directory since we will be adding an image when we generate the PDF file. Here is my sample image used that is saved on /public/img/profile.png :

Generating PDF from HTML In Symfony 5

Step 6 : Run the Application

After finishing the steps above, you can now run your application by executing the command below:

symfony server:start

After successfully running your app, open this URL in your browser:



Final Output

Generating PDF from HTML In Symfony 5