3

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.

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
user2794692
  • 361
  • 2
  • 10
  • 24

4 Answers4

3

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>
mirk
  • 442
  • 4
  • 13
2

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

Community
  • 1
  • 1
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
0

You can use absolute URL like below

<a href="{{ absolute_url(asset('uploads/YOURPATCH/'))}}pdf_download" download>
 Download 
</a>
pedram shabani
  • 1,654
  • 2
  • 20
  • 30
0

Alternative :

<a download href="{{ asset('/images/CV.pdf') }}" >Télécharger mon CV <i class="fa fa-download"></i></a>
Sacha Durand
  • 473
  • 1
  • 5
  • 11