测量矩形内的文本高度PDFsharp

时间:2014-02-22 00:22:54

标签: c# .net pdfsharp

我正在尝试使用PDFsharp布局PDF文档。我想知道如何在将文本包裹在矩形中之后返回文本的高度。这样我就可以在前一个字符串下面立即绘制一个字符串。

有关如何执行此操作的任何建议吗?

private static readonly XRect LeftRect = new XRect(10, 45, 290, 370);

public static void BuildLeftRect(this XGraphics gfx)
{
    var tf = new XTextFormatter(gfx);
    gfx.DrawRectangle(XPens.Black, LeftRect);
    tf.DrawString(GenerateAVeryLongString(), HeadingFont, XBrushes.Black, LeftRect, XStringFormats.TopLeft);
    var textMeasurement = gfx.MeasureString(GenerateAddressesText(), TextFont);
    //I want to write another string here, but the height of text measurement is the font size, not the wrapped text size. 
    Console.WriteLine(textMeasurement);
}

1 个答案:

答案 0 :(得分:1)

这并不是那么困难,我写了这个辅助函数以防其他人需要它。

private static double GetTextHeight(this XGraphics gfx, string text, double rectWidth)
        {
            var fontHeight = TextFont.GetHeight();
            var absoluteTextHeight = gfx.MeasureString(text, TextFont).Height;
            var absoluteTextWidth = gfx.MeasureString(text, TextFont).Width;

            if (absoluteTextWidth > rectWidth)
            {
                var linesToAdd = (int)Math.Ceiling(absoluteTextWidth / 290) - 1;
                return absoluteTextHeight + linesToAdd * (fontHeight);
            }
            return absoluteTextHeight;
        }

您可以这样打电话:var heightAfterWrappedInRect = gfx.GetTextHeight("text", rectWidth)