I'm generating PDF by adding single PdfPTable which accommodates multiple pages. Now I want to add header and footer to all these pages but it is only displaying on first page. Also margins are not working correctly.
I am overriding OnStartPage/OnEndPage events of class PdfPageEventHelper.
Kindly suggest best way to incorporate header and footers.
Thanks
Rule #1: don't use
OnStartPage()
to add a header or a footer. Use theOnEndPage()
method only to add both the header and the footer.Rule #2: don't add content to the
Document
object passed as a parameter to the event method. Use theDirectContent
of thePdfWriter
instead.Rule #3: read the documentation and look at the examples and Q&As marked header and footer
You'll notice that your question is a duplicate of:
This answers your question: Kindly suggest best way to incorporate header and footers.
Your question about "margins not working correctly" is probably answered here: Why is my content overlapping with my footer? However, saying "margins are not working correctly" isn't an actual question. If I tell my doctor: "I don't feel well, please help me!" I can't expect him to help me if I don't give him more info. When I add headers and footers, the margins work correctly. If it doesn't work for you, you are doing it wrong...
The same is true for your allegation that the header and footer "is only displaying on first page." That's simply not true from our point of view. If you add the event to a
PdfWriter
like this:Then the
OnEndPage()
method is invoked every time a page is finalized.