Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a New Line in iTextSharp

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();
like image 818
Andrew De Forest Avatar asked May 25 '12 14:05

Andrew De Forest


People also ask

What is chunk in iTextSharp?

A Chunk is the smallest significant piece of text that you can work with. It's ASP.NET equivalent is the <asp:Label>. As with the Label, you need to be careful how you use Chunks. The following snippet shows how to set the text of a Chunk, then write it to the PDF document 3 times: string path = Server.MapPath("PDFs");

Is iTextSharp compatible with .NET core?

The version which works with . NET core is iTextSharp. LGPLv2. Core which is free and what I use in the sample ASP.NET core project.

What is iTextSharp in C#?

Definition. Itextsharp is an advanced tool library which is used for creating complex pdf repors. itext is used by different techonologies -- Android , . NET, Java and GAE developer use it to enhance their applications with PDF functionality.

What is the use of iTextSharp DLL?

What is ITextSharp? iTextSharp is a free and open source assembly that helps to convert page output or HTML content in a PDF file. Now add that DLL in the application.


1 Answers

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();
                }
            }
        }
like image 168
Chris Haas Avatar answered Sep 29 '22 22:09

Chris Haas