Add page event listener to PDF writer : PDF Writer « PDF « Java Tutorial






import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    MyPdfPageEventHelper tracker = new MyPdfPageEventHelper();
    writer.setPageEvent(tracker);
    document.open();
    document.add(createParagraph("Fox", "Hello lazy dog."));

    document.newPage();
    HashMap lines = tracker.getLines();
    for (Iterator i = lines.keySet().iterator(); i.hasNext();) {
      String speaker = (String) i.next();
      Integer count = (Integer) lines.get(speaker);
      document.add(new Paragraph(speaker + ": " + count.intValue() + " lines."));
    }
    document.close();
  }
  private static Paragraph createParagraph(String speaker, String line) {
    Paragraph p = new Paragraph(18);
    Chunk s = new Chunk(speaker + ": ", new Font(Font.HELVETICA, 12, Font.BOLD));
    s.setGenericTag(speaker);
    p.add(s);
    p.add(line);
    return p;
  }
}
class MyPdfPageEventHelper extends PdfPageEventHelper {
  protected HashMap lines = new HashMap();

  public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
    Integer count = (Integer) lines.get(text);
    if (count == null) {
      lines.put(text, new Integer(1));
    } else {
      lines.put(text, new Integer(count.intValue() + 1));
    }
  }
  public HashMap getLines() {
    return lines;
  }
}








29.5.PDF Writer
29.5.1.PdfWriter.AllowCopy | PdfWriter.AllowPrinting
29.5.2.Set Userunit
29.5.3.Output to console with PdfWriter
29.5.4.Generates a PDF file (version 1.6) with the text 'Hello World'
29.5.5.PdfWriter.NO_SPACE_CHAR_RATIO
29.5.6.Pause and resume a writer
29.5.7.Add page event listener to PDF writer