Adding a New Line in iTextSharp

后端 未结 10 1667
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 00:36

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 c

10条回答
  •  遥遥无期
    2021-02-19 01:18

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

提交回复
热议问题