french_dev
french_dev

Reputation: 2177

issue with symfony html2pdf not rendering pdf

in my symfony project I am using Html2pdf library, and I have this code in my controller:

$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);
}

No error occures here but it renders me this:

enter image description here

So, the controller not returns a correct pdf file.

Why the html PDF render output like that ?

This the view I would like to render in 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>

This the headers response return in my browser:

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

As you can see, the content type is not application/pdf too.

Upvotes: 2

Views: 1278

Answers (2)

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3812

I think that you should return special response type

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;

Upvotes: 2

Rachid B.
Rachid B.

Reputation: 388

I had the same issue because my file was encoded in UTF-8 with BOM. If you have notepad++, just open you PHP file and look at the encoding. Then choose convert to UTF-8 without BOM.

This is a special character that is included at the top of your PHP file.

Upvotes: 0

Related Questions