C# 在 iTextSharp 中添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10756171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a New Line in iTextSharp
提问by Andrew De Forest
I've been trying to solve this problem for a while now to no avail. I have some text in iTextSharp I'm trying to put on a newline. I've tried using the \nescape character, Environment.NewLine, and document.Add(new Phrase(Environment.NewLine))without any success. So is there a way to do this? Here is the piece of my code I'm trying to do it in (note the lines commented with //Doesn't work):
我已经尝试解决这个问题一段时间了,但无济于事。我在 iTextSharp 中有一些文本,我正在尝试换行。我试过使用\n转义字符 , Environment.NewLine,document.Add(new Phrase(Environment.NewLine))但没有任何成功。那么有没有办法做到这一点?这是我尝试使用的代码片段(注意用 注释的行//Doesn't work):
//Open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
//Configure the content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont("c:\windows\fonts\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 10);
//Write the text here
cb.BeginText();
text = "F\n";//Doesn't work
document.Add(new Phrase(Environment.NewLine));//Doesn't work
text += "o\n";
text += Environment.NewLine;//Doesn't work
text += "o\n";
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 85, 311, 0);
cb.EndText();
//Create the new page
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
//Close all streams
document.Close();
fs.Close();
writer.Close();
reader.Close();
Any suggestions?
有什么建议?
Edit One:
编辑一:
Still not working with document.Add(new Paragraph("\n"));. Did I do it wrong?
仍然没有与document.Add(new Paragraph("\n"));. 我做错了吗?
cb.BeginText();
text = "F";
document.Add(new Paragraph("\n"));
text += "o";
document.Add(new Paragraph("\n"));
text += "o";
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 85, 311, 0);
cb.EndText();
采纳答案by Chris Haas
There's two main ways to work with text in iTextSharp, either through the abstractions like Paragraphand Phraseor by manually executing commands using a PdfContentByte. The abstractions will handle things like margins, line breaks and spacing while the manual route is all up to you. You can't really mix the two which is what you are doing. I'd highly recommend using the abstractions instead of the manual route unless you have a specific need for granular control. Below is a sample showing both off.
在 iTextSharp 中处理文本有两种主要方法,一种是通过抽象,如Paragraph和Phrase或通过使用PdfContentByte. 抽象将处理诸如边距、换行符和间距之类的事情,而手动路由则完全取决于您。你不能真正混合这两者,这就是你正在做的。我强烈建议使用抽象而不是手动路由,除非您对精细控制有特定需求。下面是展示两者的示例。
But to answer your question specifically, raw PDF commands (which you are using) draw text at certain x,ycoordinates from left to right and they do not support the concept of "returns" or "line breaks". To do this you need to manually move the current text cursor to a new line. See the code below for a sample of that.
但是为了具体回答您的问题,原始 PDF 命令(您正在使用)在某些x,y坐标处从左到右绘制文本,并且它们不支持“返回”或“换行符”的概念。为此,您需要手动将当前文本光标移动到新行。有关示例,请参阅下面的代码。
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//This creates two lines of text using the iTextSharp abstractions
doc.Add(new Paragraph("This is Paragraph 1"));
doc.Add(new Paragraph("This is Paragraph 2"));
//This does the same as above but line spacing needs to be calculated manually
PdfContentByte cb = writer.DirectContent;
cb.SaveState();
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12f);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "This is cb1", 20, 311, 0);
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "This is cb2", 20, 291, 0);//Just guessing that line two should be 20px down, will actually depend on the font
cb.EndText();
cb.RestoreState();
doc.Close();
}
}
}
回答by Kashif
document.Add(new Paragraph("\n"));
EDIT:
编辑:
cb.BeginText();
string text = "";
text = "F\n";
text += "o\n";
text += "o";
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 85, 311, 0);
cb.EndText();
//Create the new page
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
Paragraph p = new Paragraph(text);
document.Add(p);
//Close all streams
document.Close();
fs.Close();
writer.Close();
reader.Close();
回答by cjbarth
document.Add(new Paragraph(" "));works well for me. Remember, the Paragraphstatement automatically adds a line feed. All you have to do is give it something to render. In this case, a space will do just fine.
document.Add(new Paragraph(" "));对我来说效果很好。请记住,该Paragraph语句会自动添加换行符。你所要做的就是给它一些东西来渲染。在这种情况下,一个空格就可以了。
回答by Pieter
Try something like this:
尝试这样的事情:
document.Add(new Chunk("\n"));
回答by El Bayames
I am just trying this tool and for adding new line I just added '\r\n' and it did work. Like this below.
我只是在尝试这个工具,为了添加新行,我刚刚添加了 '\r\n' 并且它确实有效。像下面这样。
String content01 = "Nulla condimentum dui lobortis risus viverra, eu pellentesque sem blandit.\r\nUt congue turpis quis sapien mollis, vitae rutrum mi consectetur. Integer maximus nisl sed tellus pharetra pharetra.";
Phrase contentPhrase = new Phrase(content01);
Paragraph contentPr = new Paragraph();
contentPr.Add(contentPhrase);
Then added the Paragraph contentPtr to my Document instance.
然后将 Paragraph contentPtr 添加到我的 Document 实例。
回答by Pyromanci
I know this is a little old, but there is yet another way. Here is a little from one report I used.
我知道这有点旧,但还有另一种方法。这是我使用的一份报告中的一点。
var contents = new Paragraph();
contents.Alignment = Element.ALIGN_CENTER;
contents.Add(new Chunk(string.Format("{0} {1}\n", emp.FirstName, emp.LastName), new Font(baseFont, 11f, Font.BOLD)));
contents.Add(new Chunk(string.Format("Dept: {0}\n", emp.Departments.Title), new Font(baseFont, 9f)));
contents.Add(new Chunk(string.Format("Wk Ending: {0}\n", _date), new Font(baseFont, 9f)));
As you can see, what i did was create chunks. This allows you use to use "\n" to preform line breaks.
如您所见,我所做的是创建块。这允许您使用“\n”来预制换行符。
回答by spadelives
With the addition of the spacing attriubtes, you can precisely set the height of the break...
通过添加间距属性,您可以精确设置中断的高度...
var spacerParagraph = new Paragraph();
spacerParagraph.SpacingBefore = 4f;
spacerParagraph.SpacingAfter = 0f;
document.Add(spacerParagraph);
回答by Jbrown
This works perfectly for me.
这对我来说非常有效。
Dim chunkNewLine As Chunk = New Chunk(Chunk.NEWLINE)
Dim addressPhrase As New Phrase
addressPhrase.Add(chunkNewLine)
回答by Boris Luis Vasallo Lominadze
For me it worked like this:
对我来说,它是这样工作的:
document.Add(new Chunk("\n"));
worked fine, but the space was greater than I expected. so I went with this:
工作正常,但空间比我预期的要大。所以我去了这个:
document.Add(new Paragraph(" "));
the result was a fine and regular space between my components.
结果是我的组件之间有一个很好的规则空间。

