I have a app made with Symfony2 and in my twig template, I show a table with some pdf files.
This pdf files (one for user) are stored in /app/var/pdf/xxx.pdf.
If I use:
<a href="{{ 'entity.pdf' }}">PDF</a>
My path is correct, for example: symfony/app/var/pdf/123123.pdf, but when I click in the link, my browser return a 404 Not Found error. Obviusly I have checked that the file is stored in this path.
Any help?
Thanks in advance.
To force download the pdf file try this in the controller.
/**
* @Route("/download/{id}",name="pdf_download")
*/
public function downloadAction($id) {
$downloadedFile = $repository->findOneBy(
array(
'id' => $id,
)
);
$response=new Response();
$response = new Response();
$response->headers->set('Content-type', 'application/octet-stream');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $downloadedFile->getFilename() ));
$response->setContent(file_get_contents($downloadedFile->getAbsolutePath()));
$response->setStatusCode(200);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
return $response;
}
And in the template
<a href={{path('pdf_download',{'id':file.id})}}>{{file.filename}}</a>
You better need to store this file in public web dir, and then create link to it like:
<a href="{{ asset('web/var/pdf/xxx.pdf') }}"/>PDF</a>
But browsers open pdf files in new tab. And if you really want to force dowload of this file, need to use headers. Use this question for help Symfony2 - Force file download
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With