How to add text inside a rectangle?

Tags: rectangleiText 7

I have created rectangle using PdfContentByte. Now I want to add text inside this rectangle. How can I do this? My rectangle code is

 Document doc = new Document(new Rectangle(570, 924f));
 PdfWriter writer = PdfWriter.GetInstance(doc,Response.OutputStream);
 PdfContentByte cb = writer.DirectContent;
 cb.Rectangle(doc.PageSize.Width -90f, 830f, 50f,50f);
 cb.Stroke();
Posted on StackOverflow on Jul 1, 2015 by Semil Sebastian

There is no ColumnText class in iText 7, but you can set your own element area for paragraphs, using ParagraphRenderer class. Just override the initElementAreas method and write down the coordinates of the desired rectangle.

public void createPdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    PageSize ps = pdfDoc.getDefaultPageSize();
    final Rectangle rect = new Rectangle(ps.getWidth() - 90, ps.getHeight() - 100, 50, 50);
    Paragraph paragraph = new Paragraph("This is the text added in the rectangle.");
    paragraph.setNextRenderer(new ParagraphRenderer(paragraph) {
        @Override
        public List<Rectangle> initElementAreas(LayoutArea area) {
            List<Rectangle> list = new ArrayList<Rectangle>();
            list.add(rect);
            return list;
        }
    });
    doc.add(paragraph);
    doc.close();
}

Another approach is to write content directly to the Canvas object (with the desired size) through add() method:

public void createPdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    PageSize ps = pdfDoc.getDefaultPageSize();
    Paragraph p = new Paragraph("This is the text added in the rectangle.");
    PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
    Rectangle rect = new Rectangle(ps.getWidth() - 90, ps.getHeight() - 100, 50, 50);
    new Canvas(canvas, pdfDoc, rect)
            .add(p);
    canvas.rectangle(rect);
    canvas.stroke();
    pdfDoc.close();
}

Note that the Rectangle constructor now needs the following input parameters:

  • float x

  • float y

  • float width

  • float height

If the content doesn’t fit the rectangle, you can find the solution in the answer to this question: “How to fit a String inside a rectangle?”

Click this link if you want to see how to answer this question in iText 5.