Search code examples
c++podofo

Changing the font size on PoDoFo::PdfFont


I'm trying to create a searchable PDF from images that have been OCRed and in PoDoFo 0.9.22 I was able to do it with the code below. I would increase/decrease the font size till I had the correct size that matched my image. But as of 0.10.x (I'm trying to use 0.10.3) there is no GetFontSize anywhere and PdfFont does not have SetFontSize. How can I achieve the same thing in the new version?

Thanks

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 = pFont->GetFontSize();
    double tmpW = fontMetrics->StringWidth(aText);

    while (tmpW < txtBB.Width)
    {
        fontSize += 1.0;
        pFont->SetFontSize(fontSize);
        tmpW = fontMetrics->StringWidth(aText);
    }
    while (tmpW > txtBB.Width)
    {
        fontSize -= 0.5;
        pFont->SetFontSize(fontSize);
        tmpW = fontMetrics->StringWidth(aText);
    }
    mPainter.DrawText(txtBB.Left, (pageBB.Height) - (txtBB.Top + txtBB.Height), aText);
}

Solution

  • I was able to find the answer. It turns out all the font related functionality has been moved to the TextState property of PdfPainter and PdfPainter itself does NOT have GetFontSize() or SetFont() function. So the function that I posted in my question (which worked in version 0.9.x), has to become like the function below to work in version 0.10.x.

    void PrintTextOnPage(PoDoFo::PdfPainter& mPainter, PoDoFo::PdfFont* pFont, const TRectD& pageBB,
        const PoDoFo::PdfString aText, const TRectD& txtBB)
    {
        double fontSize = mPainter.TextState.GetFontSize();
        PoDoFo::PdfTextState tmpState = {pFont, fontSize, 1.0, 0.0, 0.0, PoDoFo::PdfTextRenderingMode::Invisible};
        double tmpW = pFont->GetEncodedStringLength(aText, tmpState);
    
        while (tmpW < txtBB.Width)
        {
            fontSize += 1.0;
            tmpState.FontSize = fontSize;
            tmpW = pFont->GetEncodedStringLength(aText, tmpState);
        }
        while (tmpW > txtBB.Width)
        {
            fontSize -= 0.5;
            tmpState.FontSize = fontSize;
            tmpW = pFont->GetEncodedStringLength(aText, tmpState);
        }
        mPainter.TextState.SetFont(*pFont, fontSize);
        mPainter.DrawText(aText, txtBB.Left, (pageBB.Height) - (txtBB.Top + txtBB.Height), PoDoFo::PdfDrawTextStyle::Regular);
    }