Set PageEvent to Pdf document : Page Event « PDF « Java Tutorial






import java.io.FileOutputStream;

import com.lowagie.text.Document;
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.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass extends PdfPageEventHelper {
  BaseFont bf;

  public void onOpenDocument(PdfWriter arg0, Document arg1) {
    try {
      bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
      bf = null;
    }
  }

  public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    Rectangle pageSize = writer.getPageSize();
    Rectangle art = writer.getBoxSize("bleed");
    cb.rectangle(art.left(), art.bottom(), art.width(), art.height());
    cb.stroke();
    cb.setLineWidth(3);
    cb.restoreState();
  }

  public static void main(String[] args) throws Exception {
    Document document = new Document(new Rectangle(432, 792));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    writer.setViewerPreferences(PdfWriter.PageLayoutTwoPageLeft);
    writer.setPageEvent(new MainClass());
    writer.setCropBoxSize(new Rectangle(5, 5, 427, 787));
    writer.setBoxSize("bleed", new Rectangle(30, 30, 402, 762));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    ColumnText ct = new ColumnText(cb);
    Paragraph p = new Paragraph();
    for (int i = 0; i < 10; i++) {
      p.add(new Phrase("test "));
    }
    for (int i = 0; i < 10; i++) {
      ct.addElement(p);
    }
    int status = ColumnText.NO_MORE_COLUMN;
    while (ColumnText.hasMoreText(status)) {
      ct.setSimpleColumn(72, 72, 360, 684);
      status = ct.go();
      document.newPage();
    }
    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