How to download pdf file from public folder in symfony?

Member

by brandy , in category: PHP Frameworks , 3 months ago

How to download pdf file from public folder in symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 3 months ago

@brandy 

To download a PDF file from a public folder in Symfony, you can follow these steps:

  1. Create a route in your Symfony routes configuration file (e.g., config/routes.yaml) to handle the download request: pdf_download: path: /download/pdf/{filename} controller: AppControllerDownloadController::pdfDownload
  2. Create a controller class (e.g., DownloadController) to handle the download request. In this controller, define a method (e.g., pdfDownload) to retrieve the PDF file from the public folder and send it as a response: namespace AppController; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentHttpFoundationResponse; use SymfonyComponentHttpFoundationBinaryFileResponse; use SymfonyComponentHttpFoundationResponseHeaderBag; class DownloadController extends AbstractController { public function pdfDownload($filename) { $pdfPath = $this->getParameter('kernel.project_dir') . '/public/pdf/' . $filename; return new BinaryFileResponse($pdfPath); } }
  3. Place your PDF file in the public folder (e.g., public/pdf/) of your Symfony project.
  4. Now, you can use the generated route to download the PDF file by accessing the following URL pattern: http://localhost/download/pdf/{filename} Replace {filename} with the actual name of your PDF file.


When a user accesses the download URL, Symfony will retrieve the PDF file from the public folder and send it as a response to the browser, prompting the user to download the file.