【问题标题】:dompdf getTextWidth() get correct string width for custom fontdompdf getTextWidth() 获取自定义字体的正确字符串宽度
【发布时间】:2021-12-10 11:06:22
【问题描述】:

如何获得自定义字体的正确字符串宽度?

我正在使用barryvdh/laravel-dompdf (v0.9.0) 创建具有自定义字体的 PDF。但我的问题与纯 dompdf (v1.0.2) 相同。

我需要计算 PDF 中字符串的宽度,以确保它适合页面。我使用load_font.php 安装了字体并创建了 .ufm 文件(AdobeFontMetrics?)。

现在我尝试计算 PDF 中的字符串宽度:

$pdf->getDomPDF()->getFontMetrics()
  ->getTextWidth($title, 'itc avant garde pro', 32, 0.0, 0.0)

HTML 包含以下内容:

<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>

我在文本下方有一个绿色条来比较宽度。

如果我创建两个长度相同的字符串,我的绿色条 getTextWidth() 不会返回相同的宽度。

$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

我尝试了 CPDF 和 PDFLib 后端。我还尝试手动更改 .ufm 文件,但这对 getTextWidth() 没有任何影响。

如何为我的字体获得正确的字符串宽度?

【问题讨论】:

  • dompdf 有一个字体度量表,其中包含所有字符的宽度。它正在使用它来创建 pdf,getTextWidth() 使用相同的功能和宽度,但不知何故它不起作用......

标签: php laravel dompdf


【解决方案1】:

getTextWidth()的第二个参数不是字符串。这真的是字体本身。还要确保获得正确的字体粗细。

这行得通:

$font = $pdf->getDomPDF()->getFontMetrics()->getFont('itc avant garde pro', 'bold');
$pdf->getDomPDF()->getFontMetrics()
  ->getTextWidth($title, $font, 32, 0.0, 0.0)

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 2015-12-30
    • 1970-01-01
    • 2012-09-16
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多