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:

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:

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: