import java.awt.Color;
import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
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"));
writer.setPageEvent(new MyPdfPageEventHelper());
document.open();
Paragraph p = new Paragraph();
Chunk fox = new Chunk("test");
fox.setGenericTag("box");
p.add(fox);
p.add(" this is a test ");
Chunk dog = new Chunk("test ");
dog.setGenericTag("ellipse");
p.add(dog);
document.add(p);
document.close();
}
}
class MyPdfPageEventHelper extends PdfPageEventHelper {
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
if ("ellipse".equals(text)) {
PdfContentByte cb = writer.getDirectContent();
cb.setRGBColorStroke(0xFF, 0x00, 0x00);
cb.ellipse(rect.left(), rect.bottom() - 5f, rect.right(), rect.top());
cb.stroke();
cb.resetRGBColorStroke();
} else if ("box".equals(text)) {
PdfContentByte cb = writer.getDirectContentUnder();
rect.setBackgroundColor(new Color(0xa5, 0x2a, 0x2a));
cb.rectangle(rect);
}
}
}