How To Generate PDF File In Symfony
For this tutorial we will use Dompdf as pdf library. Although there are many PDF libraries out there, this is one of the best because is very easy to implement in your project. To generate your first PDF with thi library you will need to create a new folder and inside it we will create the file which will contain our HTML for the PDF file.
Generate PDF using Dompdf
<html> <head> <meta charset="UTF-8"> <title>Generate PDF File</title> </head> <body> <h4>{{ headline }}</h4> <p>Description</p> </body> </html>
Now, we have the html for pdf, now we should proceed to install the library in symfony and use it in controller.
To install Dompdf run the following command with composer:
composer require dompdf/dompdf
After the installation is ready you will be able to use the the library in all your controllers. The only thing you will need to do is send all data you need in your PDF to the twig file we created earlier.
The following php code is all you need to generate the pdf:
public function generate_pdf(){ $options = new Options(); $options->set('defaultFont', 'Roboto'); $dompdf = new Dompdf($options); $data = array( 'headline' => 'my headline' ); $html = $this->renderView('pdf/pdf.html.twig', [ 'headline' => "Test pdf generator" ]); $dompdf->loadHtml($html); $dompdf->setPaper('A4', 'portrait'); $dompdf->render(); $dompdf->stream("testpdf.pdf", [ "Attachment" => true ]); }
As you can see is very easy to generate a pdf using dompdf, you can check all options available on github. The only part that is not so good is it will be a bit difficult to debug the code when you will make the implementation in twig file.
hello .. kindly asking does this code takes the view page and then generates it as is into pdf?