使用itext而不是第一页为每页PDF添加文本

时间:2015-02-15 17:08:28

标签: c# itext

我正在尝试使用此代码将文本添加到PDF的每个页面,但该代码仅用于向第一页添加文本:

            //variables
        String pathin = @"C:\Users\root\Desktop\temp\test.pdf";
        String pathout = @"C:\Users\root\Desktop\temp\test2.pdf";

//create a document object
//var doc = new Document(PageSize.A4);
//create PdfReader object to read from the existing document
PdfReader reader = new PdfReader(pathin);

//create PdfStamper object to write to get the pages from reader 
PdfStamper stamper=new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
// PdfContentByte from stamper to add content to the pages over the original content
PdfContentByte pbover = stamper.GetOverContent(1);
//add content to the page using ColumnText
ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase("Hello World"), 10, 10, 0);
// PdfContentByte from stamper to add content to the pages under the original content
//PdfContentByte pbunder = stamper.GetUnderContent(1);

//close the stamper
stamper.Close();

我见过使用的例子:

   for (var i = 1; i <= reader.NumberOfPages; i++)
                    {
                        document.NewPage();

                        var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                        var importedPage = writer.GetImportedPage(reader, i);

要遍历每个页面,但我无法将其绑定到上面的代码中。非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

在您的第一个代码段中,您对页码进行了硬编码:

 stamper.GetUnderContent(1);

在你的第二个片段中,你遍历页面:

for (var i = 1; i <= reader.NumberOfPages; i++)  {
}

现在结合这两个片段:

for (var i = 1; i <= reader.NumberOfPages; i++)  {
       PdfContentByte pbunder = stamper.GetUnderContent(i);
       // do stuff with bunder
}