iTextSharp - Header and Footer for all pages

2019-07-11 09:44发布

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

1条回答
倾城 Initia
2楼-- · 2019-07-11 10:40

Rule #1: don't use OnStartPage() to add a header or a footer. Use the OnEndPage() 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 the DirectContent of the PdfWriter 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:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Header event = new Header();
writer.setPageEvent(event);

Then the OnEndPage() method is invoked every time a page is finalized.

查看更多
登录 后发表回答