6

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

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

如果文本长于 ,这将换行textAreaWidth

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

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

感谢您的任何提示。

4

3 回答 3

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;
}

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

于 2016-10-11T09:53:26.193 回答
3

The XTextFormatter class (source code included with PDFsharp) is meant to get you started. Modify it if it doesn't suit your needs.

Since XTextFormatter keeps the Y position internally, it would be a rather simple change to return the height of the text that was just drawn.

Instead of modifying XTextFormatter, consider using MigraDoc Foundation (also included) instead.

于 2013-03-18T14:09:45.933 回答
1

我发现 PdfSharp 的这个扩展可以解决这个问题:

http://developer.th-soft.com/developer/2015/07/17/pdfsharp-improving-the-xtextformatter-class-measuring-the-height-of-the-text/

您可以在此处克隆或分叉相关代码:

https://github.com/yolpsoftware/PdfSharp/tree/measure-text-height

于 2016-09-08T14:59:39.037 回答