tags:

views:

251

answers:

1

I use itext.dll for genrating a PDF using ASP.NET and I want a footer in my document in the form of:

    Page 1 of 6 

    HeaderFooter footer = new HeaderFooter(new Phrase("Page"), new Phrase(" of 6")); 
    footer.setBorder(Rectangle.NO_BORDER); 
    footer.setAlignment(Element.ALIGN_CENTER); 
    document.setFooter(footer);

Is this possible without hardcoding the total number of pages? I.e. is there a method to get the total number pages in a document?

+2  A: 

I have found that there are (at least) 2 ways of doing this.

One is to create the document without the footer and after that use PdfStamper to stamp the page numbers with total on it. But that raised some problems with me when I output the stampers product to MemoryStream and there seems to be no way of closing the stamper without closing the stream at the same time.

The other way is to create one instance of PdfTemplate that will represent the total page count and add that to every page to footer or where ever you want it.

Next you can use your own PdfPageEventHelper class and implement OnCloseDocument method where you can fill the template with total page count:

public override void OnCloseDocument(PdfWriter writer, Document document)
{
    PageCountTemplate.BeginText();
    PageCountTemplate.SetFontAndSize(HeaderFont.BaseFont, HeaderFont.Size);
    PageCountTemplate.ShowText((writer.CurrentPageNumber - 1).ToString());
    PageCountTemplate.EndText();
}

I personally also use OnOpenDocument to create the template and OnEndPage to write it on each page.

EDIT: To answer Jan's question, OnCloseDocument is called only once when the whole doc has been written. When Doc.Close() is called I mean.

Juhani Markkula
will OnCloseDocument called for each page or just the doc?
Jan Wikholm