In my Symfony 2 project, I would like to display a pdf in the browser when the user clicks on a link for viewing a pdf file. The pdf files are contained in my "views" folder, in a subfolder called "pdf-files".
How do I need to adapt the following controller function so that a pdf file gets displayed in the browser?
/**
* @Route("/pdf/{pdfFilename}")
*/
public function pdfAction($pdfFilename) {
return $this->render('@App/pdf-files/'.$pdfFilename);
}
It's all about conten-type header of http request. So just set it:
$response = $this->render('@App/pdf-files/'.$pdfFilename);
$response->headers->set('Content-Type', 'application/pdf');
return $response;
To serve static file you might want to use BinaryFileResponse class. In such response you can set content disposition
- is this file should be opened in a browser or downloaded as an attachment.
So your code should look something like:
public function pdfAction($pdfFilename)
{
$kernel = $this->get('kernel');
$path = $kernel->locateResource('@AppBundle/Resources/pdf-files/'.$pdfFilename);
$response = new BinaryFileResponse($path)
$response->headers->set('Content-Type', 'application/pdf');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE, //use ResponseHeaderBag::DISPOSITION_ATTACHMENT to save as an attachement
$pdfFilename
);
return $response;
}
EDIT: since locateResource is looking for files under Resources
directory by default I would suggest moving your pdf-files
directory from views
directory to Resources