Saintjah
Saintjah

Reputation: 153

Adding text to each page of PDF with itext instead of just the first page

I'm trying to add text to each page of a PDF using this code which works great, but this code is only for adding text to the first page:

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

I've seen examples using:

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

To iterate through each page, but I'm having trouble tying that into my code above. Any helps would be much appreciated, thanks.

Upvotes: 1

Views: 3246

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

in your first snippet, you hardcode the page number:

 stamper.GetUnderContent(1);

In your second snippet, you loop over the pages:

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

Now combine these two snippets:

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

Upvotes: 2

Related Questions