itext Page events (iText 5) versus Event handlers and Renderers (iText 7)


Suppose that you have the following text file: jekyll_hyde.txt

How do we convert it to a PDF that looks like this:

enter image description here

Note that this is very similar to what we had before, but the border of the titles now has rounded corners. We created a custom ParagraphRenderer to achieve this, and we created a TitleParagraph object that uses that renderer:

public class TitleParagraph extends Paragraph {

    public TitleParagraph(String line) {
        try {
        catch (IOException ioe) {

    protected IRenderer makeNewRenderer() {
        return new ParagraphRenderer(this) {
            public void drawBorder(DrawContext drawContext) {
                Rectangle occupiedAreaBBox = getOccupiedAreaBBox();
                float[] margins = getMargins();
                Rectangle rectangle = applyMargins(occupiedAreaBBox, margins, false);
                PdfCanvas canvas = drawContext.getCanvas();
                canvas.roundRectangle(rectangle.getX() - 1, rectangle.getY() - 1,
                rectangle.getWidth() + 2, rectangle.getHeight() + 2, 5).stroke();

Our code to convert text to PDF is very simple now. We no longer have to set the font to bold for the titles and we no longer have to define a border:

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new Footer());
    Document document = new Document(pdf)
    BufferedReader br = new BufferedReader(new FileReader(TEXT));
    String line;
    PdfFont normal = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
    boolean title = true;
    Border border = new SolidBorder(Color.BLUE, 1);
    while ((line = br.readLine()) != null) {
        if (title)
            document.add(new TitleParagraph(line));
            document.add(new Paragraph(line).setFont(normal));
        title = line.isEmpty();

Source: and the iText 7: Building Blocks tutorial.