Search code examples
javapdfitextrectangles

Adding text to a rectangle in PDF using itext5


PdfContentByte canvas = writer.getDirectContent();
Rectangle rect = new Rectangle(0, 805, 594, 820);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(1);
rect.setBackgroundColor(BaseColor.GRAY);
rect.setBorderColor(BaseColor.GREEN);

ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);

ct.addElement(new Paragraph("Your Text Goes here!! ",catFont));
ct.go();
canvas.rectangle(rect);

document.newPage();
document.close();

This is my code, here I'm trying to add text in rectangle. It didn't work! the rectangle is created but the text is not dispalyed anywhere on the pdf page.


Solution

  • There are a couple of issues with your code causing the text not to show.

    Firstly, you add the rectangle to the canvas AFTER you add the text. The gray background will go over any text that was drawn, hiding it.

    Secondly, your font size is too big for column boundary, so no text is shown. You can make your rectangle larger and the text will show or decrease the size of your font.

    For example, the following should work as I have increased the rectangle height and moved the canvas.rectangle() call to before the ColumnText.go():

    Rectangle rect = new Rectangle(0, 780, 494, 820);
    rect.setBorder(Rectangle.BOX);
    rect.setBorderWidth(1);
    rect.setBackgroundColor(BaseColor.GRAY);
    rect.setBorderColor(BaseColor.GREEN);
    canvas.rectangle(rect);
    
    ColumnText ct = new ColumnText(canvas);
    ct.setSimpleColumn(rect);
    Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    ct.addElement(new Paragraph("Your Text Goes here!! ", catFont));
    ct.go();