Tuesday, October 9, 2012

Add Header and Footer to PDF

Before start to work out on this topic. I want to give some concept regarding iText PDF.

1. onStartPage() : It is auto triggerd method when new page started. If pdf has 10 page then it would be execute 10 times. Used this method to initializing variable or setting parameter. But it is not right place add Header and Footer.

2. onEndPage() : It is also auto triggered method during before starting a new page. This is right place to add Header and Footer.


To use these method, class should be extended by com.lowagie.text.pdf.PdfPageEventHelper;


HeaderAndFooter.java


import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderAndFooter extends PdfPageEventHelper{
 
protected Phrase header;
protected PdfPTable footer;
 
public static void main(String[] args) {
new HeaderAndFooter().createPDF();
System.out.println("** PDF CREATED **");
}
public void createPDF() {
Document document = new Document();
try{
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("Header_Footer_Example.pdf"));
writer.setPageEvent(new HeaderAndFooter());
document.open();
for(int i=0;i<1000;i++){
document.add(new Phrase("BINOD KUMAR SUMAN "));
}
document.close();
}catch(Exception e){
}
}
public HeaderAndFooter() {
header = new Phrase("**** THIS IS HEADER PART OF THIS PDF ****");
footer = new PdfPTable(1);
footer.setTotalWidth(300);
footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
footer.addCell(new Phrase(new Chunk("**** THIS IS FOOTER PART OF THIS PDF ****")
.setAction(new PdfAction(PdfAction.FIRSTPAGE))));
}
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(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);
}
}

Here one problem is that header will start from first page itself. If you want that header should come from second page. Then you have to put one condition like this

if (document.getPageNumber() > 1) {ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(document.right() - document.left()) / 2+ document.leftMargin(), document.top() + 10, 0);}

0 comments:

Post a Comment