You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PoDoFo 0.10.x版本中如何调整PdfFont字体大小适配OCR图像?

PoDoFo 0.10.x 版本实现文本宽度匹配图像区域的方案

在PoDoFo 0.10.x版本中,PdfFont不再维护字体大小状态,字体大小改为由**绘图上下文(PdfPainter)**控制,同时计算字符串宽度时需要显式传入字体大小参数。以下是适配后的代码:

void PrintTextOnPage(PoDoFo::PdfPainter& mPainter, PoDoFo::PdfFont* pFont, const TRectD& pageBB, const PoDoFo::PdfString aText, const TRectD& txtBB)
{
    const PoDoFo::PdfFontMetrics* fontMetrics = pFont->GetFontMetrics();
    // 初始化基础字体大小,可根据需求调整初始值
    float fontSize = 10.0f;
    double tmpW = fontMetrics->StringWidth(aText, fontSize);

    // 放大字体直到宽度接近目标区域
    while (tmpW < txtBB.Width)
    {
        fontSize += 1.0f;
        tmpW = fontMetrics->StringWidth(aText, fontSize);
    }
    // 缩小字体直到宽度匹配目标区域
    while (tmpW > txtBB.Width)
    {
        fontSize -= 0.5f;
        tmpW = fontMetrics->StringWidth(aText, fontSize);
    }

    // 绘制前绑定字体并设置目标大小
    mPainter.SetFont(pFont);
    mPainter.SetFontSize(fontSize);
    mPainter.DrawText(txtBB.Left, (pageBB.Height) - (txtBB.Top + txtBB.Height), aText);
}

关键变化说明

  • 字符串宽度计算:新版本PdfFontMetrics::StringWidth必须传入fontSize参数,不再依赖PdfFont的内部状态
  • 字体大小控制:通过PdfPainter::SetFontSize在绘制阶段临时设置,无需修改PdfFont对象本身
  • 初始值设定:由于无法从PdfFont获取默认字体大小,需手动指定一个合理的初始值(如示例中的10.0f)

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:55:14