symfony html2pdf无法呈现pdf的问题

时间:2016-02-18 11:17:36

标签: php html5 symfony pdf html2pdf

在我的symfony项目中我使用的是Html2pdf库,我的控制器中有这个代码:

$html = $this->render('MyBundle:MyFolder:myPDF.html.twig', array('slug' => $slug));

$html->getContent();

try {
  $html2pdf = new \Html2Pdf_Html2Pdf('P', 'A4', 'fr', true, 'UTF-8');
  $html2pdf->pdf->SetAuthor('....');
  $html2pdf->pdf->SetDisplayMode('real');
  $html2pdf->writeHTML($html);
  $html2pdf->Output('Bill.pdf');
  $response = new Response();

  $response->headers->set('Content-type', 'application/pdf');

  return $response;

} catch(HTML2PDF_exception $e) {

  die($e);
}

这里没有错误,但它让我这样:

enter image description here

因此,控制器不会返回正确的pdf文件。

为什么html PDF会像那样呈现输出?

这是我想用pdf呈现的视图:

<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta name="description" content="Bill">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

    <body>
      <table>
          <thead>
              <tr>
                  <th>test</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td>test</td>
              </tr>
          </tbody>
      </table>
  </body>

此标题响应在我的浏览器中返回:

HTTP/1.1 500 Internal Server Error
Date: Thu, 18 Feb 2016 13:05:16 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.12
x-powered-by: PHP/5.5.12
Cache-Control: public, must-revalidate, max-age=0, no-cache
Pragma: public
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Last-Modified: Thu, 18 Feb 2016 13:05:17 GMT
Content-Length: 2198
Content-Disposition: inline; filename="Bill.pdf";
X-Debug-Token: 5e207b
X-Debug-Token-Link: /symfony/web/app_dev.php/_profiler/5e207b
Connection: close
Content-Type: text/html; charset=UTF-8

如您所见,内容类型也不是application / pdf。

2 个答案:

答案 0 :(得分:1)

我认为您应该返回特殊回复类型

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
....
$response = new BinaryFileResponse('/file/path/file.pdf');
$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_INLINE,
    'file.pdf',
    iconv('UTF-8', 'ASCII//TRANSLIT', 'file.pdf')
);

return $response;

答案 1 :(得分:0)

我遇到了同样的问题,因为我的文件是用带有BOM的UTF-8编码的。 如果你有notepad ++,只需打开PHP文件并查看编码。 然后选择转换为UTF-8而不使用BOM。

这是一个包含在PHP文件顶部的特殊字符。