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.