tags:

views:

1371

answers:

1

This is weird, I am currently using iTextSharp and I want to add a Header & Footer to my PDFs. In all the examples they simply create a new HeaderFooter() object. However, I have iTextSharp libraries all imported but the HeaderFooter is not defined. I've used Reflector to see if I can find out whereabouts the class is and its missing?!

Does anyone know what has happened to this class?

+3  A: 

Most of the examples refer to an earlier version of iTextSharp. For version 5+ of iTextSharp (which I assume you are using) the HeaderFooter property/object has been removed.

See http://itextpdf.com/history.php?branch=history.50&node=500 (last line)

To add Headers/Footers now you must use PageEvents. The following code demonstrates how to do this in VB. You basically have to inherit the PageEventsHelper class and watch for the OnStartPage event - then add your code as necessary.

Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.IO
Module Module1
    Sub Main()
        Dim pdfDoc As New Document()
        Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("tryme2.pdf", FileMode.Create))
        Dim ev As New itsEvents
        pdfWrite.PageEvent = ev
        pdfDoc.Open()
        pdfDoc.Add(New Paragraph("Hello World"))
        pdfDoc.NewPage()
        pdfDoc.Add(New Paragraph("Hello World Again"))
        pdfDoc.Close()
    End Sub
End Module

Public Class itsEvents
    Inherits PdfPageEventHelper
    Public Overrides Sub OnStartPage(ByVal writer As iTextSharp.text.pdf.PdfWriter, ByVal document As iTextSharp.text.Document)
        Dim ch As New Chunk("This is my Stack Overflow Header on page " & writer.PageNumber)
        document.Add(ch)
    End Sub
End Class

It initially looks like more work but has the upside that you can add more to your header/footer than just plain text. You can now for example easily add anything that Document will support.

CResults