How can I get the correct string width for my custom font?
I am using barryvdh/laravel-dompdf (v0.9.0) to create PDFs with a custom font. But I the problem is the same with pure dompdf (v1.0.2).
I need to calculate the width of string in the PDF to make sure it fits into the page. With load_font.php I installed the font and created .ufm files (AdobeFontMetrics?).
Now I try to calculate the string width in the PDF:
$pdf->getDomPDF()->getFontMetrics()
->getTextWidth($title, 'itc avant garde pro', 32, 0.0, 0.0)
HTML contains this:
<style>
h1 {
font-family: 'itc avant garde pro', serif;
font-size: 32px;
letter-spacing: 0;
word-spacing: 0;
}
</style>
<h1 style="margin: 0">WWWWWWWWWWWWWWWWW</h1>
<h1 style="margin: 0">BBBBBBBBBBBBBBBBBBBBBBBBBB</h1>
<div style="background-color:green; height: 20px; width: 539px;"></div>
I have a green bar below the text to compare width.
If I create two strings with the same length as my green bar getTextWidth()
does not return the same width.
$title = 'WWWWWWWWWWWWWWWWW";
// is the almost same length as the bar and getTextWidth() returns 522.24
$title = 'BBBBBBBBBBBBBBBBBBBBBBBBBB';
// is the almost same length as the bar and getTextWidth() returns width 477.568
I tried CPDF and PDFLib backend. Also I tried to manually change .ufm files but that does not have any affect on getTextWidth()
.
How can I get the correct string width for my font?
The second parameter of getTextWidth()
is not a string. It is really the font itself. Also make sure to get the correct font weight.
This worked:
$font = $pdf->getDomPDF()->getFontMetrics()->getFont('itc avant garde pro', 'bold');
$pdf->getDomPDF()->getFontMetrics()
->getTextWidth($title, $font, 32, 0.0, 0.0)