Calculate text height based on available width and

2020-02-10 03:18发布

We are creating PDF documents on the fly from the database using PDFsharp.

I need to know the best way to calculate the height of the text area based on the font used and the available width.

I need to know the height so I can process page breaks when required.

8条回答
我命由我不由天
2楼-- · 2020-02-10 03:54

I had a similiar problem so I implemented this extension method:

public static double MeasureHeight(this PdfSharp.Drawing.XGraphics gfx, string text, PdfSharp.Drawing.XFont font, int width)
{
    var lines = text.Split('\n');

    double totalHeight = 0;

    foreach (string line in lines)
    {
        var size = gfx.MeasureString(line, font);
        double height = size.Height + (size.Height * Math.Floor(size.Width / width));

        totalHeight += height;
    }

    return totalHeight;
}
查看更多
地球回转人心会变
3楼-- · 2020-02-10 04:00

In .NET you can call Graphics.MeasureString to find out how large the drawn text is going to be.

查看更多
登录 后发表回答