This Class add page number on the header of each page of the PDF File.

___________HeaderAndFooter.JAVA______________________________

import com.itextpdf.text.Chunk;

import com.itextpdf.text.Document;

import com.itextpdf.text.Element;

import com.itextpdf.text.Phrase;

import com.itextpdf.text.pdf.ColumnText;

import com.itextpdf.text.pdf.PdfAction;

import com.itextpdf.text.pdf.PdfContentByte;

import com.itextpdf.text.pdf.PdfPTable;

import com.itextpdf.text.pdf.PdfPageEventHelper;

import com.itextpdf.text.pdf.PdfWriter;

public class HeaderAndFooter extends PdfPageEventHelper {

protected Phrase header;

protected PdfPTable footer;

 

public HeaderAndFooter() {

header = new Phrase("**** Header ****");

footer = new PdfPTable(1);

footer.setTotalWidth(150);

footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

footer.addCell(new Phrase(new Chunk(

"**** Footer summary Report generated by JavaGenious****")

.setAction(new PdfAction(PdfAction.FIRSTPAGE))));

}

public void onEndPage(PdfWriter writer, Document document) {

PdfContentByte cb = writer.getDirectContent();

ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(String.format("%d", writer.getPageNumber()),

redFont), (document

.right() - document.left())

/ 2 + document.leftMargin(), document.top() + 10, 0);

footer.writeSelectedRows(0, -1,

(document.right() - document.left() - 300) / 2

+ document.leftMargin(), document.bottom() - 10, cb);

}

}

___________________________________________

This class can be invoked from below code:

________________________________________________________

Document document = new Document();

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE));

writer.setPageEvent( new HeaderAndFooter());

document.open();


Enter your email address:

Delivered by FeedBurner



Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)