Page X of Y issue

Your second way is probably the simplest way. Below is a very, very slimmed down but working version:

public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper {
    public override void OnEndPage(PdfWriter writer, Document document) {
        ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(writer.PageNumber.ToString()), 500, 140, 0);
    }
}

And to use it:

//Create a file on our desktop
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "OnCloseTest.pdf");
//Standard PDF creation, adjust as needed
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (Document doc = new Document(PageSize.LETTER)) {
        using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {

            //Find our custom event handler
            writer.PageEvent = new MyPdfPageEventHelpPageNo();

            doc.Open();

            //Add text the first page
            doc.Add(new Paragraph("Test"));

            //Add a new page with more text
            doc.NewPage();
            doc.Add(new Paragraph("Another Test"));

            doc.Close();
        }
    }
}

EDIT

Sorry, I thought that you were having problems with the basic setup of events, my mistake.

I’ve only seen two ways to do what you are trying to do, either do two passes or use the PdfTemplate syntax which renders an image as far as I know.

I’d recommend just running two passes, the first just to create your PDF and the second to add your page numbers. You can run your first pass to a MemoryStream so you don’t have to hit the disk twice if you want.

PdfReader reader = new PdfReader(outputFile);
using (FileStream fs = new FileStream(secondFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (PdfStamper stamper = new PdfStamper(reader, fs)) {
        int PageCount = reader.NumberOfPages;
        for (int i = 1; i <= PageCount; i++) {
            ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase(String.Format("Page {0} of {1}", i, PageCount)), 500, 140, 0);
        }
    }
}

Leave a Comment