views:

6603

answers:

2

Hi,

I'm trying to create a footer on each of the pages in a PDF document using iTextSharp in the format Page # of # following the tutorial on the iText pages and the book. Though I keep getting an exception on cb.SetFontAndSize(helv, 12); - object reference not set to an object. Can anyone see the issue? Code is below.

Thanks, Rob

public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper
{
    protected PdfTemplate total;
    protected BaseFont helv;
    private bool settingFont = false;

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        total = writer.DirectContent.CreateTemplate(100, 100);
        total.BoundingBox = new Rectangle(-20, -20, 100, 100);

        helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    }

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        PdfContentByte cb = writer.DirectContent;
        cb.SaveState();
        string text = "Page " + writer.PageNumber + " of ";
        float textBase = document.Bottom - 20;
        float textSize = 12; //helv.GetWidthPoint(text, 12);
        cb.BeginText();
        cb.SetFontAndSize(helv, 12);
        if ((writer.PageNumber % 2) == 1)
        {
            cb.SetTextMatrix(document.Left, textBase);
            cb.ShowText(text);
            cb.EndText();
            cb.AddTemplate(total, document.Left + textSize, textBase);
        }
        else
        {
            float adjust = helv.GetWidthPoint("0", 12);
            cb.SetTextMatrix(document.Right - textSize - adjust, textBase);
            cb.ShowText(text);
            cb.EndText();
            cb.AddTemplate(total, document.Right - adjust, textBase);
        }
        cb.RestoreState();
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        total.BeginText();
        total.SetFontAndSize(helv, 12);
        total.SetTextMatrix(0, 0);
        int pageNumber = writer.PageNumber - 1;
        total.ShowText(Convert.ToString(pageNumber));
        total.EndText();
    }

}
+8  A: 

Here's a good example for adding total page number to every page.

Muxa
+1  A: 

The Above code is correct the only problem is, it is not being executed, for that u have to create a instance at the place where you have written a code for Downloading PDf. Example:

MyPdfPageEventHelpPageNo pageeventhandler = new MyPdfPageEventHelpPageNo(); writer.PageEvent = pageeventhandler;

writer means PDF writer(a instance)

You can get a help at Example basic usage

Go to its Advance Usage and you will find the exact code and tips.

Abhishek Jain