【问题标题】:issue with symfony html2pdf not rendering pdfsymfony html2pdf 不呈现 pdf 的问题
【发布时间】:2016-02-18 11:17:35
【问题描述】:

在我的 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);
}

这里没有发生错误,但它呈现给我:

因此,控制器没有返回正确的 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。

【问题讨论】:

    标签: php html symfony pdf html2pdf


    【解决方案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;
    

    【讨论】:

    • BinaryFileResponse 给我同样的回报。谢谢你的建议。
    • 尝试手动设置内容配置 - 我更新了我的回复。
    • 而不是 $this->render 使用 $this->renderView 它将返回字符串而不是响应对象。也许它弄乱了响应。并向我们​​展示您的响应 http 标头。
    • 向我们展示该 pdf 响应的 http 标头 - 他们可以帮助解决该问题。
    【解决方案2】:

    我遇到了同样的问题,因为我的文件是用带有 BOM 的 UTF-8 编码的。 如果您有记事本++,只需打开您的 PHP 文件并查看编码。 然后选择convert to UTF-8 without BOM。

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

    【讨论】:

    • 我试过你的建议,结果还是一样。
    猜你喜欢
    • 2012-04-18
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多