3

How do I return a response in Symfony to output a pdf? I'm currently using FPDF as I don't want to use any bundles. Here is my controller action:

public function pdfAction(Request $request) {

    //grab from database

    $pdf = new \FPDF;

    for($i = 0; $i < count($entities); $i++) {
        //manipulate data

       $pdf->AddPage();
       $pdf->SetFont("Helvetica","","14");
       $pdf->SetTextColor(255, 255, 255);
    }

    $pdf->Output();

    return new Response($pdf, 200, array(
        'Content-Type' => 'pdf'));

}

With this all I'm getting is a page with gibberish characters. I'm quite new to I/O manipulations so any help would be great. Thank you..

2 Answers 2

9

You need to set proper Content-Type of your response. Also, don't send your FPDF object as a content of your response, but rather the PDF output. Try this:

public function pdfAction(Request $request) {

    //................//

    return new Response($pdf->Output(), 200, array(
        'Content-Type' => 'application/pdf'));

}

UPDATE:

To get your generated PDF file downloaded instead of displayed, you need to set disposition to attachment:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

public function pdfAction(Request $request) {

    //................//

    $response = new Response(
        $pdf->Output(),
        Response::HTTP_OK,
        array('content-type' => 'application/pdf')
    );

    $d = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        'foo.pdf'
    );

    $response->headers->set('Content-Disposition', $d);

    return $response;
}

http://symfony.com/doc/current/components/http_foundation/introduction.html#serving-files

Sign up to request clarification or add additional context in comments.

2 Comments

so simple. Thank you! How can I get the file to be downloaded instead of it showing on the browser?
Original answer (update not tested) works with Symfony 4 too.
2

In symfony 2.7, I'm having a "Corrupted content" while trying to set the Content-Disposition. My fix is:

public function pdfAction(Request $request) {

//................//

$response = new Response(
    $pdf->Output(),
    Response::HTTP_OK,
    array('content-type' => 'application/pdf')
);

return $response;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.