Adding a New Line in iTextSharp

左心房为你撑大大i 提交于 2020-06-24 21:23:13

问题


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 \n escape 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):

//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?

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();

回答1:


There's two main ways to work with text in iTextSharp, either through the abstractions like Paragraph and Phrase or 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.

But to answer your question specifically, raw PDF commands (which you are using) draw text at certain x,y coordinates 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.

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



回答2:


Try something like this:

document.Add(new Chunk("\n"));



回答3:


document.Add(new Paragraph(" ")); works well for me. Remember, the Paragraph statement 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.




回答4:


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();



回答5:


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



回答6:


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.




回答7:


I am just trying this tool and for adding new line I just added '\r\n' and it did work. Like this below.

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.




回答8:


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.




回答9:


This works perfectly for me.

Dim chunkNewLine As Chunk = New Chunk(Chunk.NEWLINE)
Dim addressPhrase As New Phrase
addressPhrase.Add(chunkNewLine)



回答10:


Maybe it's an iText 7 thing (which is the version I am using), but the suggestions above did not work for me. What did was:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Paragraph p = new Paragraph();
. . .
p.Add("WHEELWORK!");
p.Add("\n\n"); // break two lines
p.Add("Ezekiel's Vision");
p.Add("\n"); // break one line
. . .
doc.Add(p);


来源:https://stackoverflow.com/questions/10756171/adding-a-new-line-in-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!