package pdfReport;

import java.awt.Color;
import com.lowagie.text.Document;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

/**
 * This class writes page numbers in the pdf document
 * @author 
 *
 */
public class PageNumbersWatermark extends PdfPageEventHelper {
	/** An Image that goes in the header. */
    public Image headerImage;
    /** The headertable. */
    public PdfPTable table;
    /** The Graphic state */
    public PdfGState gstate;
    /** A template that will hold the total number of pages. */
    public PdfTemplate tpl;
    /** The font that will be used. */
    public BaseFont helv;
    
    /**
     * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
     */
    public void onOpenDocument(PdfWriter writer, Document document) {
        try {
        	
            // initialization of the template
            tpl = writer.getDirectContent().createTemplate(120, 120);
            tpl.setBoundingBox(new Rectangle(0, 0, 120, 120));
            // initialization of the font
            helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
        }
        catch(Exception e) {
            throw new ExceptionConverter(e);
        }
    }    
    
    /**
     * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
     */
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        // compose the footer except for the first page
        if(writer.getPageNumber() != 1){
	        String text = "" + writer.getPageNumber();
	        float textSize = helv.getWidthPoint(text, 12);
	        float textBase = document.bottom() - 20;
	        cb.beginText();
	        cb.setFontAndSize(helv, 12);
	        float adjust = helv.getWidthPoint("0", 12);
	        cb.setTextMatrix(document.right() - textSize - adjust, textBase);
	        cb.showText(text);
	        cb.endText();
	        cb.addTemplate(tpl, document.right() - adjust, textBase);
	        cb.saveState();
        }
        // draw a Rectangle around the page
        cb.setColorStroke(Color.gray);
        cb.setLineWidth(0);
        cb.rectangle(20, 20, document.getPageSize().width() - 40, document.getPageSize().height() - 40);
        cb.stroke();
        cb.restoreState();
    }    
    
}
