PdfSharp 的这个扩展对我来说不太适用。不知道为什么,但我的身高一直比预期的要高(几乎是所需身高的两倍)。所以我决定为 XGraphics 对象编写一个扩展方法,我可以在其中指定一个 maxWidth 并在内部计算软换行符。该代码使用XGraphics.MeasureString(string, XFont)
内联文本的默认宽度并与文本中的单词聚合来计算换行符。计算软换行符的代码如下所示:
/// <summary>
/// Calculate the number of soft line breaks
/// </summary>
private static int GetSplittedLineCount(this XGraphics gfx, string content, XFont font, double maxWidth)
{
//handy function for creating list of string
Func<string, IList<string>> listFor = val => new List<string> { val };
// string.IsNullOrEmpty is too long :p
Func <string, bool> nOe = str => string.IsNullOrEmpty(str);
// return a space for an empty string (sIe = Space if Empty)
Func<string, string> sIe = str => nOe(str) ? " " : str;
// check if we can fit a text in the maxWidth
Func<string, string, bool> canFitText = (t1, t2) => gfx.MeasureString($"{(nOe(t1) ? "" : $"{t1} ")}{sIe(t2)}", font).Width <= maxWidth;
Func<IList<string>, string, IList<string>> 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