che*_*ica 6 c# pdf pdf-generation pdfsharp
PDFSharp 在绘制长文本部分时支持自动文本换行:
textFormatter.DrawString(text, font, XBrushes.Black, new XRect(x, y, textAreaWidth, 1000), XStringFormats.TopLeft);
Run Code Online (Sandbox Code Playgroud)
如果文本长于,这将换行 textAreaWidth.
如何获取刚刚绘制的文本的高度?
我用 尝试过gfx.MeasureString(),但没有支持指定最大宽度的重载。gfx.MeasureString()返回没有文本换行的文本大小。
感谢您的任何提示。
小智 6
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;
}
Run Code Online (Sandbox Code Playgroud)
完整代码见以下要点:https : //gist.github.com/erichillah/d198f4a1c9e8f7df0739b955b245512a