Calculate text height based on available width and font?

前端 未结 8 1518
醉酒成梦
醉酒成梦 2020-12-16 13:11

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 use

8条回答
  •  时光取名叫无心
    2020-12-16 14:01

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

提交回复
热议问题