Generating PDF in Codeigniter 4 - outputs weird characters

2k views Asked by At

I'm generating a PDF document in my Codeigniter4 application.

I installed TCPDF via composer: composer require tecnickcom/tcpdf

My pdf is created the standard way, nothing fancy there.

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');
$pdf->SetMargins(10, 10, 10);
$pdf->SetTextColor(33, 65, 108);
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();
...

Everything is working as expected unless I try to output the PDF.

$pdf->Output("file.pdf", 'D'); gives me the option to download the file and it is a correct PDF file as I would wish.

But if I try to output it directly in the browser:

$pdf->Output("file.pdf", 'I');

In the output I get weird characters. Looks like the document binary content is echoed to the browser, ignoring the header Content-Type. I'm not sure, but i think it is a Codeigniter 4 issue, because in CI3 this code works, also not using CI, just plain PHP gives me the desired result.

What's wrong with CI4, is there some option to turn on?

1

There are 1 answers

0
Dusan On BEST ANSWER

As @marcogmonteiro suggested, I have to force CI to output the correct headers:

$this->response->setHeader("Content-Type", "application/pdf");
$pdf->Output("file.pdf", 'I');