PDFSharp:用自动换行测量长文本的高度

PDFSharp在绘制长文本部分时支持自动文本换行:

textFormatter.DrawString(text, font, XBrushes.Black, new XRect(x, y, textAreaWidth, 1000), XStringFormats.TopLeft); 

如果文本长于textAreaWidth这将包装文本。

如何获得刚刚绘制的文本的高度?

我尝试使用gfx.MeasureString() ,但没有支持指定最大宽度的重载。 gfx.MeasureString()返回文本的大小而不进行文本换行。

谢谢你的任何提示。

XTextFormatter类(PDFsharp附带的源代码)旨在帮助您入门。 如果它不符合您的需要,请进行修改。

由于XTextFormatter在内部保持Y位置,因此返回刚刚绘制的文本的高度将是一个相当简单的更改。

不要修改XTextFormatter,而是考虑使用MigraDoc Foundation(也包括在内)。

PdfSharp的这种扩展对我来说并不适用。 不知道为什么,但我保持比预期更高的高度(几乎是所需高度的两倍)。 所以我决定在XGraphics对象中编写一个扩展方法,我可以在其中指定maxWidth并在内部计算软换行符。 代码使用默认的XGraphics.MeasureString(string, XFont)来内联文本Width和Aggregates以及文本中的单词来计算换行符。 计算软换行符的代码如下所示:

 ///  /// Calculate the number of soft line breaks ///  private static int GetSplittedLineCount(this XGraphics gfx, string content, XFont font, double maxWidth) { //handy function for creating list of string Func> listFor = val => new List { val }; // string.IsNullOrEmpty is too long :p Func  nOe = str => string.IsNullOrEmpty(str); // return a space for an empty string (sIe = Space if Empty) Func sIe = str => nOe(str) ? " " : str; // check if we can fit a text in the maxWidth Func canFitText = (t1, t2) => gfx.MeasureString($"{(nOe(t1) ? "" : $"{t1} ")}{sIe(t2)}", font).Width <= maxWidth; Func, string, IList> appendtoLast = (list, val) => list.Take(list.Count - 1) .Concat(listFor($"{(nOe(list.Last()) ? "" : $"{list.Last()} ")}{sIe(val)}")) .ToList(); var splitted = content.Split(' '); var lines = splitted.Aggregate(listFor(""), (lfeed, next) => canFitText(lfeed.Last(), next) ? appendtoLast(lfeed, next) : lfeed.Concat(listFor(next)).ToList(), list => list.Count()); return lines; } 

有关完整代码,请参阅以下要点: https : //gist.github.com/erichillah/d198f4a1c9e8f7df0739b955b245512a