Search code examples
phpfontscharmpdf

generating pdf with MPDF, non breaking space displayed as unsupoprted characters


Using Mpdf 8.0.8, I create a document with custom font which displays fine, except for non-breaking spaces, which appear as crossed-squares:enter image description here

When opening my font with FontForge I see that uni00A0 char is defined (it's blank but there is no cross)

Here is the code calling Mpdf:

public function getPdfData($values, $medias, $locale = 'fr_FR')
{
    $sessionLocale = $this->translator->getLocale();
    $this->translator->setLocale($locale);
    $html = $this->twig->render('@Pim/testPdf.html.twig');
    $this->translator->setLocale($sessionLocale);

    $defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
    $fontDirs = $defaultConfig['fontDir'];

    $defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
    $fontData = $defaultFontConfig['fontdata'];

    $fontData = $fontData + [
            'myhelvet' => [
                'R' => 'helvetlight.ttf',
                'I' => 'helvetthick.ttf',
            ],
            'timeslightitalic' => [
                'R' => 'timeslightitalic.ttf'
            ]
        ];
    $defaultFont = 'myhelvet';

    $mpdf = new \Mpdf\Mpdf([
        'orientation' => 'L',
        'margin_left' => 0,
        'margin_right' => 0,
        'margin_top' => 1,
        'margin_bottom' => 0,
        'fontDir' => array_merge($fontDirs, [
            __DIR__ . '/../Resources/public/fonts',
        ]),
        'fontdata' => $fontData,
        'default_font' => $defaultFont,
        'mode' => '+aCJK',
        "autoScriptToLang" => true,
        "autoLangToFont" => true,
    ]);
    $mpdf->addFontDirectory(__DIR__ . '/../Resources/public/fonts');
    $mpdf->WriteHTML($html);
    $pdfData = $mpdf->Output('', 'S');

    return $pdfData;
}

And here goes the html view that cannot render a non breaking space created by Php NumberFormatter:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<div style="font-family: myhelvet">Formatting a number: {{ '20000'|numberFormatLocale('fr_FR') }}</div>

</body>
</html>

Finally, the php code generating the breaking space (a Twig filter):

public static function numberFormatLocale($number, $locale)
{
    $formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);

    return $formatter->format($number);
}

Solution

  • The output of the NumberFormatter is not U+00A0, but 0xE2 0x80 0xAf, or U+202F - NARROW NO-BREAK SPACE which is most likely not supported by the font.