Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCPDF for PHP creates empty PDF when special (slovic) character đ is used

I'm using TCPDF to generate PDFs (obviously). All has been well, but now I'm trying to make a PDF with the character "đ" (which apparently is a slovic character).

The data is user-generated, so I won't know if they're planning on using these type of characters or not - that's why I thought I should use UTF-8. But apparently that's not right.

The PDF gets created, but it's completely empty / white.

Here is my relevant code:

$pdf = new XTCPDF('P', PDF_UNIT, 'Letter', true, 'UTF-8', false);
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins($pageMargin, $pageMargin, $pageMargin); //PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT
$pdf->SetAutoPageBreak(TRUE, $pageMargin/2);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetFont('helvetica', '', 10, '', true);

$pdf->AddPage();

$pdf->setJPEGQuality(70);

I found this answer but changing to this didn't work either:

$pdf = new XTCPDF('P', PDF_UNIT, 'Letter', false, 'ISO-8859-1', false);

My data pieces (user's name, address...etc) are currently wrapped like this:

trim(mb_convert_encoding($myHtml, "HTML-ENTITIES", "UTF-8"))

Questions:

What can I change to make it so that:

  1. I can create a PDF with a character like "đ"
  2. I can make the settings so it will create regardless of the character(s) the user uses.
like image 578
Dave Avatar asked Mar 16 '23 01:03

Dave


1 Answers

David van Driessche has correctly identified the problem; the font in use doesn't support the đ character.

A basic test (note that I saved this PHP script as a UTF8 file):

require './tcpdf/tcpdf.php';

function write($pdf)
{
    $pdf->Write(0, 'test đ   ', '', 0, '', false, 0, false, false, 0);
    $pdf->writeHTML(trim(mb_convert_encoding('test2 đ', "HTML-ENTITIES", "UTF-8")), true, false, true, false, '');
}

$pdf = new TCPDF('P', PDF_UNIT, 'Letter', true, 'UTF-8', false);
$pdf->AddPage();

$pdf->SetFont('helvetica', '', 20);
write($pdf);

$pdf->SetFont('freesans', '', 20);
write($pdf);

$pdf->Output();

This gives me the following PDF output (rendered in Firefox):

PDF result

Looking at the TCPDF example for including an external UTF-8 text file you can see the following very interesting line:

$pdf->SetFont('freeserif', '', 12);

Strangely freeserif is not listed as one of the standard TCPDF fonts but is in the fonts folder distributed with TCPDF (looking in this folder led me to freesans as well, so I used that in the example above). I can only assume the documentation is not up-to-date.

It seems your choices are to either use freesans or load a third-party font via the AddFont() method.

Edit: I tested the above with a slightly older build of TCPDF: 6.0.099.

like image 96
timclutton Avatar answered Apr 06 '23 12:04

timclutton