Returning a PDF document from a Symfony controller

Published on 2021-07-04 • Modified on 2021-07-04

In this snippet, we see how to return a PDF document from a Symfony controller. We are going to use the spipu/html2pdf library. I don't use a dedicated bundle here; we use the BinaryFileResponse provided by Symfony to create the response. The setContentDisposition() function tells if the file is displayed (DISPOSITION_INLINE) or downloaded (DISPOSITION_ATTACHMENT) and also to set a specific name instead of using the temporary one.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Spipu\Html2Pdf\Html2Pdf;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet153Trait
{
    public function snippet153(): Response
    {
        $tmpFileName = (new Filesystem())->tempnam(sys_get_temp_dir(), 'sb_', '.pdf');

        $html = '<h1>Strangebuzz.com</h1><br/><table border="1"><tr><td>COil</td><td>Col2</td></tr></table>';

        (new Html2Pdf())->writeHTML($html)->output($tmpFileName, 'F');

        return (new BinaryFileResponse($tmpFileName, Response::HTTP_OK))
            ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'example.pdf');

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!