I am new to ItextSharp, just wondering how to place header and footer outside the margin after end of page event? it seems when i used the onendpage event instead of adding the
As you are new to iText... when you are looking for samples concerning some specific topic, you should first go and look into the Keyword list for samples from iText in Action — 2nd Edition. In your case the keyword Header / footer is appropriate. The first sample referenced there, part1.chapter05.MovieHistory2, already shows you how to add headers and footers in general.
First of all, as you already have mentioned yourself, you should use page events, onEndPage
to be exact, which most easily is done by extending PdfPageEventHelper.
Furthermore, as according to your question you seem not to be aware of, you should not add headers or footers by calling document.add
or something similar because such additions go into the main page area which already is finished now (we're in onEndPage
after all...). Instead you should position the headers and footers using direct content access.
The sample does it like this:
/**
* Adds the header and the footer.
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
* com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("art");
switch(writer.getPageNumber() % 2) {
case 0:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, header[0],
rect.getRight(), rect.getTop(), 0);
break;
case 1:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, header[1],
rect.getLeft(), rect.getTop(), 0);
break;
}
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}
ColumnText.showTextAligned
allows you to position headers, footers, etc. exactly where you want them on the page, outside the top and bottom margins normally, without causing any new pages to be generated or any other unwanted effects.
found it, i just use columntext, though i really like not to use columntext :) and use the setsimplecolumn.