【问题标题】:Adding a New Line in iTextSharp在 iTextSharp 中添加新行
【发布时间】:2012-06-01 03:21:20
【问题描述】:

我已经尝试解决这个问题一段时间了,但无济于事。我在 iTextSharp 中有一些文本,我正在尝试换行。我尝试使用\n 转义字符、Environment.NewLinedocument.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();

有什么建议吗?

编辑一:

仍然无法使用 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();

【问题讨论】:

    标签: c# itextsharp newline


    【解决方案1】:

    在 iTextSharp 中处理文本有两种主要方法,一种是通过 ParagraphPhrase 之类的抽象,另一种是使用 PdfContentByte 手动执行命令。抽象将处理诸如边距、换行符和间距之类的事情,而手动路由完全取决于您。您不能真正将两者混合在一起,这就是您正在做的事情。除非您特别需要精细控制,否则我强烈建议您使用抽象而不是手动路由。下面是一个显示两者都关闭的示例。

    但要具体回答您的问题,原始 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();
                    }
                }
            }
    

    【讨论】:

    • 感谢您的澄清!
    • 很好的解释,克里斯,谢谢。
    【解决方案2】:

    试试这样的:

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

    【讨论】:

    • 想解释一下您的解决方案是做什么的?这是一篇质量很低的帖子。
    • @Anzeno 它的作用是查看并添加一个带有换行符的新chuck() 到文档中。不多解释。
    【解决方案3】:

    document.Add(new Paragraph(" ")); 很适合我。请记住,Paragraph 语句会自动添加换行符。你所要做的就是给它一些东西来渲染。在这种情况下,空格就可以了。

    【讨论】:

      【解决方案4】:
      document.Add(new Paragraph("\n"));
      

      编辑:

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

      【讨论】:

      • 仍然显示一行,请参阅编辑...也许我做错了?
      • 仍然在同一行,尽管如果您检查 Chris 的答案,这可能是 iText 软件的技术限制。尽管如此,我还是感谢您的帮助!
      【解决方案5】:

      加上间距属性,可以精确设置断点的高度...

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

      【讨论】:

        【解决方案6】:

        对我来说是这样的:

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

        工作正常,但空间比我预期的要大。所以我选择了这个:

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

        结果是我的组件之间有一个细而规则的空间。

        【讨论】:

          【解决方案7】:

          我只是在尝试这个工具,为了添加新行,我刚刚添加了 '\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);
          

          然后将段落 contentPtr 添加到我的 Document 实例中。

          【讨论】:

            【解决方案8】:

            我知道这有点老了,但还有另一种方法。这是我使用的一份报告中的一小部分。

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

            如您所见,我所做的是创建块。这允许您使用“\n”来执行换行符。

            【讨论】:

              【解决方案9】:

              这对我来说非常有效。

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

              【讨论】:

                【解决方案10】:

                也许这是 iText 7 的东西(这是我正在使用的版本),但上面的建议对我不起作用。做了什么:

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

                【讨论】:

                  猜你喜欢
                  • 2015-08-13
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-11-11
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-11-30
                  相关资源
                  最近更新 更多