Search code examples
phpcssfontsmpdf

Arial font looks different from HTML to a mpdf conversion


There must be something I don't know about how fonts work, a lot of things actually. May be someone can explain me why if the font in my css is set like "font-family: Arial, Helvetica, sans-serif;"

Why does it look a little different? In the pdf look stretched and rounder. Are there different types of the same font? If that's the case how can I fix it?

HTML page: enter image description here

PDF page: enter image description here

This is what I'm applying to the html to print with mpdf

h1
{
text-align: center;
margin-top: 90px;
margin-bottom: 90px;
text-transform: uppercase;
font-family: Arial, Helvetica, sans-serif;
font-weight: normal;
font-size: 23vw;
}




$htmlStringView = view('pdf-view', ['content' => $content, 'cssString' => $cssString])->render();

$contract = $this->userContractRepository->show($id);
$mpdf = new Mpdf(['tempDir' => '/var/www/storage/temp', 'format' => [198, 280]]);
$contract = $this->addJsonDataToModelAttributes($contract);
$mpdf->SetHTMLFooter('<div style="text-align: right;">{PAGENO}/{nbpg}</div>');
$mpdf->WriteHTML($htmlStringView);
$mpdf->SetTitle($contract->title);
$mpdf->SetAuthor($contract->owner->email);
$mpdf->SetSubject(implode(", ", $contract->persons->pluck('full_name')->toArray()));
$mpdf->SetKeywords($id);
$mpdf->Output('/var/www/storage/app/' . $full_path);

Solution

  • Arial is not by default included in mPDF distribution, replacement is DejavuSans. If needed, you have to point your mPDF instance to the font file.

    $defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
    $fontDirs = $defaultConfig['fontDir'];
    
    $defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
    $fontData = $defaultFontConfig['fontdata'];
    
    $mpdf = new \Mpdf\Mpdf([
        'tempDir' => '/var/www/storage/temp',
        'format' => [198, 280],
        'fontDir' => array_merge($fontDirs, [
            __DIR__ . '/custom/font/directory',
        ]),
        'fontdata' => $fontData + [
            'arial' => [
                'R' => 'arial.ttf',
                'I' => 'arial-italic.ttf',
            ]
        ],
    ]);
    

    see https://mpdf.github.io/fonts-languages/fonts-in-mpdf-7-x.html