Pdf Page Event Helper : Page Event « PDF « Java Tutorial





import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass extends PdfPageEventHelper {
  protected PdfTemplate total;

  protected BaseFont helv;

  public void onOpenDocument(PdfWriter writer, Document document) {
    total = writer.getDirectContent().createTemplate(100, 100);
    total.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    try {
      helv = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
      throw new ExceptionConverter(e);
    }
  }

  public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    String text = "Page " + writer.getPageNumber() + " of ";
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    cb.showText(text);
    cb.endText();
    cb.restoreState();
  }

  public void onCloseDocument(PdfWriter writer, Document document) {
    total.beginText();
    total.setFontAndSize(helv, 12);
    total.setTextMatrix(0, 0);
    total.showText(String.valueOf(writer.getPageNumber() - 1));
    total.endText();
  }

  public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    writer.setPageEvent(new MainClass());
    document.open();
    Paragraph p = new Paragraph();
    for (int k = 1; k <= 3000; ++k) {
      p.add(new Phrase("test"));
    }
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    for (int k = 1; k <= 12; ++k) {
      document.add(p);
    }
    document.close();
  }
}










29.22.Page Event
29.22.1.extends PdfPageEventHelper
29.22.2.Pdf document footer
29.22.3.Pdf Page Event Helper
29.22.4.Set PageEvent to Pdf document
29.22.5.Pdf events: on chapter, on chapter end, on section, on document Close Document
29.22.6.Transition and Duration