PDFsharp换行

35

我想在字符串中添加新行,但是如果我使用\n,它不起作用。

有没有办法通过向字符串添加类似于\r\n的内容来实现换行(这也不起作用)?

gfx.DrawString("Project No \n" + textBoxProjNumber.Text, fontUnder, XBrushes.Black, 230, 95);

(示例代码显示了我尝试过的内容,但没有成功)。


如果这是一种控制台模式,那么调用DrawString()两次怎么样? - BlackBear
2
尝试为要打印的每一行调用DrawString(),例如DrawString("项目编号"); DrawString(textBoxProj.....); - BlackBear
那个可以运行,但我必须检查是否有 \n 然后从那里开始绘制新的字符串。 - Afnan Bashir
2个回答

43

你尝试过使用XTextFormatter类吗?

请看这里: http://www.pdfsharp.net/wiki/TextLayout-sample.ashx

代码片段:

PdfDocument document = new PdfDocument();

PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Times New Roman", 10, XFontStyle.Bold);
XTextFormatter tf = new XTextFormatter(gfx);

XRect rect = new XRect(40, 100, 250, 220);
gfx.DrawRectangle(XBrushes.SeaShell, rect);
tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft);

1
这个可以运行。谢谢。还有一个问题,在migradoc中如何让它检测到段落是否超过一页,并自动插入分页符。 - Afnan Bashir
2
我刚发现的一件事(我知道pdfsharp已被更好的库所取代),但在VB.net中,您必须使用+ vbNewLine而不是/n。 - ShiftyThomas
4
@ShiftyThomas,我很好奇哪些“更好的库”取代了pdfSharp?请分享一下! - ctb
2
@ctb 我认为 pdfSharp 已经停止更新了,所以有几次我在使用它时遇到了一些 bug 却无能为力。我现在使用 http://sourceforge.net/projects/itextsharp/ 一段时间了,但他们已经改为付费许可证。对于轻量级的需求,我用过 http://www.stefanochizzolini.it/en/projects/clown/index.html。 - ShiftyThomas
1
他在谈论换行,而不是分页。 - Patrick Borkowicz
显示剩余4条评论

2

以下是我所做的,不涉及使用Rect类:

我有一个定义好的右侧限制,并确定当前字符串是否大于设置的边界。如果是,我就写下来。否则,我继续添加。

foreach (string field in temp)
{
    if (field == string.Empty)
    {
        continue;
    }
    else
    {
        tempSB.Clear();
        tempSB.Append(sb.ToString());
        tempSB.Append(field).Append(", ");  //append the incoming value to SB for size testing

        if (gfx.MeasureString(tempSB.ToString(), defaultFont).Width > 500)  //if the incoming string is bigger than the right bounds, write it and clear SB
        {
            gfx.DrawString(sb.ToString(), defaultFont, blackBrush, 50, currentLine + defaultSpacing);
            currentLine += 15;
            sb.Clear();
            sb.Append(" " + field).Append(",");  //add the overflow to the beginning of the next line
         }
         else
         {
             sb.Append(field).Append(", ");  //if it is not too big, append it
         }
     }

 }
 if (sb.Length > 0 && sb[sb.Length - 1] == ',') sb.Length--;
 gfx.DrawString(sb.ToString(), defaultFont, blackBrush, 50, currentLine + defaultSpacing); //write out whatever has not already been written out

我知道我来晚了,但我希望这能对某人有所帮助。


类似于XTextFormatter类的方法,但灵活性较差。 - I liked the old Stack Overflow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接