如何在Symfony中返回响应以输出pdf?我目前正在使用FPDF,因为我不想使用任何捆绑包。这是我的控制器动作:
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'));
}
有了这一切,我得到的是一个带有乱语字符的页面。我对I / O操作很陌生,所以任何帮助都会很棒。谢谢..
答案 0 :(得分:5)
您需要设置适当的Content-Type
回复。另外,请勿将FPDF
对象作为回复内容发送,而是发送PDF输出。试试这个:
public function pdfAction(Request $request) {
//................//
return new Response($pdf->Output(), 200, array(
'Content-Type' => 'application/pdf'));
}
<强>更新强>
要下载生成的PDF文件而不是显示,您需要将disposition
设置为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
答案 1 :(得分:2)
在symfony 2.7中,我有一个&#34;已损坏的内容&#34;在尝试设置Content-Disposition时。我的修复是:
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
return $response;
}