2014-02-22 25 views
1

我想要使用PDFsharp來佈置PDF文檔。我想知道如何在文本被包裝在一個矩形後返回文本的高度。這樣我可以在前一個字符串下面立即繪製一個字符串。在矩形內測量文本高度PDFsharp

有關如何做到這一點的任何建議?

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

這並不是那麼困難,我寫了這個幫助函數以防其他人需要它。

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)

+0

不需要調用gfx.MeasureString兩次 - 一次調用它,結果分配給一個變量。字面意思是「290」的目的是什麼? –

+0

這是列的絕對寬度。 –

+0

我預計。爲什麼不使用rectWidth而不是290?僅在單詞之間出現換行符,這種簡單的計算不會總是有效。因此,向XTextFormatter添加一個out參數將是更好,更通用的解決方案。另請參閱:http://stackoverflow.com/a/15478864/1015447 –