How to generate PDF in Symfony 4.2
Nowadays, PDF generation is a much-needed feature for every e-commerce website. Whether we need to create an invoice or a set of guidelines for a product, this feature is a must-have for your website. In a recent Symfony based project, I had to work on creating PDF from HTML in Twig and CSS and I am going to share the step by step approach that I followed for the purpose.
Installing Symfony 4.2:
For this tutorial, I am going to show the installation of the Symfony 4.2 (latest version) using composer and you need to run the following command for the purpose:
composer create-project symfony/website-skeleton pdf
￼After installation, use the PHP built-in webserver command to run the project as mentioned below:
php bin/console server:run
Open the browser and navigate to:
Installing PDF library:
There are many libraries available for generating pdf from HTML. Let’s use Snappy (wkhtmltopdf) library for the purpose of understanding because as it’s simple yet effective.
To install Snappy, the following command has to be executed in the terminal:
composer require knplabs/knp-snappy-bundle
In order to run and use Snappy, we need to install wkhtmltopdf 0.12.x (available for OSX, Linux and Windows) by running the following command:
sudo apt-get install wkhtmltopdf
Now we have to enable KnpSnappybundle in bundles of Symfony as follows:
Next, we need to add the Snappy config to the bin path
Create file knp_snappy.yaml in /config/packages
Note: binary path may vary.
Generating PDF from Twig
Now that all the requirements have been fulfilled, we can start to generate PDF from Twig file. I created DefaultController.php and pdf template.html.twig for this tutorial.
We are good to go now! Just hit the URL http://127.0.0.1:8000/pdf and you will get a prompt to download a pdf file.
After you have downloaded pdf, you can see the HTML we set in /templates/pdf_template.html.twig
Found the article useful? Share it with your friends and co-workers… Now!