How to generate a pdf file

I’m coding a site on symfony, and I need help to generate a pdf and open in the browser when I click on a button.

But it isn’t working and I really don’t know why
It would be really kind of you if you could help me please

Here is the code in myAccount.html.twig
<a id="facture" href=" {{path('make_pdf')}} "><span class="material-icons ">request_page</span></a>

Here is the code in the controller

     * @Route("/facture", name="make_pdf")
     * generate pdf and open in browser
     */
    public function makePdf()
    {
        // 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('location/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
        ]);
    }

And here is the code in location/mypdf.html.twig

<html>
    <head>
        <meta charset="UTF-8">
        <title>Title of the PDF</title>
    </head>
    <body>
        <h4>{{ title }}</h4>
        <p>Lorem Ipsum</p>
    </body>
</html>

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *