English 中文(简体)
在 iTextSharp 中添加新行
原标题: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 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
";//Doesn’t work
document.Add(new Phrase(Environment.NewLine));//Doesn’t work
text += "o
";
text += Environment.NewLine;//Doesn’t work
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);

//Close all streams
document.Close();
fs.Close();
writer.Close();
reader.Close();

有什么建议吗?

<强>编辑一:

Still not working with document.Add(new Paragraph(" "));. Did I do it wrong?

cb.BeginText();
text = "F";
document.Add(new Paragraph("
"));
text += "o";
document.Add(new Paragraph("
"));
text += "o";
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 85, 311, 0);
cb.EndText();
最佳回答

使用 iTextSharp 文本的两种主要方法,要么是通过 < code> 第 和 < code> Phrase 等抽象方法,要么通过使用 < code> PdfcontentByte 手动执行命令。当手动路径完全由您决定的时候,这些抽象方法将处理边距、线间距和间距等事项。您无法真正将您正在做的这两个组合起来。我强烈建议使用抽象而不是手动路径,除非您对颗粒控制有特定需要。下面是显示两者的样本。

但具体回答您的问题, 原始 PDF 命令( 您正在使用) 从左到右在某些 < code> 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();
                }
            }
        }
问题回答

尝试一下这样的东西:

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

document.Add(新段落(")"); 语句对我很好。记住, 段的语句会自动添加线性种子。你只需要给它一些东西来做。在这种情况下,一个空间会很好。

document.Add(new Paragraph("
"));

<强度 > EDIT:

cb.BeginText();
string text = "";
text = "F
";           
text += "o
";            
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();

加上分节间距,您可以精确设定间断的高度...

var spacerParagraph = new Paragraph();
spacerParagraph.SpacingBefore = 4f;
spacerParagraph.SpacingAfter = 0f;
document.Add(spacerParagraph);

对我来说,它的工作是这样的:

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

工作良好,但空间比我预期的要大。 所以我用这个:

document.Add(new Paragraph(" "));

结果是在我的部件之间 形成了一个优雅和正常的空间

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

String content01 = "Nulla condimentum dui lobortis risus viverra, eu pellentesque sem blandit.
Ut 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);

然后在我的文档实例中添加段落内容Ptr 。

我知道这有点老了,但还有别的办法。这是我用过的一份报告中的一点。

            var contents = new Paragraph();
            contents.Alignment = Element.ALIGN_CENTER;

            contents.Add(new Chunk(string.Format("{0} {1}
", emp.FirstName, emp.LastName), new Font(baseFont, 11f, Font.BOLD)));
            contents.Add(new Chunk(string.Format("Dept: {0}
", emp.Departments.Title), new Font(baseFont, 9f)));
            contents.Add(new Chunk(string.Format("Wk Ending:  {0}
", _date), new Font(baseFont, 9f)));

As you can see, what i did was create chunks. This allows you use to use " " to preform line breaks.

这对我很管用

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

也许这是iText 7的东西(这就是我使用的版本),但上述建议对我行不通。

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Paragraph p = new Paragraph();
. . .
p.Add("WHEELWORK!");
p.Add("

"); // break two lines
p.Add("Ezekiel s Vision");
p.Add("
"); // break one line
. . .
doc.Add(p);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签