footer text and page numbers in itextsharp

Dramoth picture Dramoth · Nov 22, 2012 · Viewed 7.4k times · Source

I have a PDF document where, usually, each page is stamped with a footer with a page number preceded by the name of the chapter or section that the page should be in. However, occasionally, I get some large table results that span over a number of pages.

I need to maintain the footer stamp for the current section they are in but because of the large tables running over a number of pages, those pages are getting stamped with the previous sections footer stamp and the last page that the table is displayed on gets the current sections footer stamp.

If anyone can come up with a solution towards setting and maintaining a chapter/section footer stamp for the current section that would be great.

* Additional * Here is the code for the onEndPage overide.

public override void OnEndPage(PdfWriter writer, Document document)
{
    base.OnEndPage(writer, document);

    if ((pagenumber - 1) >= 1)
    {
        String text = footer + pagenumber.ToString();
        float len = bf.GetWidthPoint(text, 8);

        Rectangle pageSize = document.PageSize;

        cb.SetRGBColorFill(100, 100, 100);

        cb.BeginText();
        cb.SetFontAndSize(bf, 8);
        cb.SetTextMatrix(pageSize.GetRight(100), pageSize.GetBottom(20));
        cb.ShowText(text);
        cb.EndText();
        if (this.currentChapter > this.totalChapters)
        {
            pagenumber = 0;
        }
        else
        {
            pagenumber++;
        }
    }
    else
    {
        pagenumber++;
    }
}

I skip adding the header and footer information for the document because I have a cover page. Because the various parts are disparate information, I have broken them down into chapters and subsections based on the various areas. Also, the users have the option of printing out a number of PDF's at once generated from database information. And at the start of each chapter, I set the footer text using the following command:

this.PageEventHandler.footer = "(Part 1) - Page: ";

Or at least I am trying to. When it comes to doing the second section (Employment History), if a person has been swapped around various departments a lot in their employment history they can build up quite a record and it overflows onto several pages.

Answer

Echilon picture Echilon · Nov 22, 2012

One way of doing this is to use PdfPageEvents to add the footer as each page as it's processed. The documentation is for the Java version, but you need to override the onEndPage method.

iTextPDF - PdfPageEvent