Skip to main content
Skip table of contents

How to truncate text within a bounding box?

How can I stop the text from overflowing a given region when writing?

I am writing content to a PdfContentByte object directly using:


I'd like to know how I can stop the text overflowing a given region when writing. If possible it would be great if iText could also place an ellipsis character where the text does not fit. I can't find any method on ColumnText that will help either. I do not wish the content to wrap when writing.

Posted on StackOverflow on Nov 26, 2012 by Brett Ryan

Please take a look at the TrucateTextInCell example. It shows how to solve your problem using iText 7. We override the layout() method in CellRenderer class and it will be triggered every time a Cell is added on which we used the setNextRenderer() method.

public LayoutResult layout(LayoutContext layoutContext) {
    PdfFont bf = getPropertyAsFont(Property.FONT);
    float availableWidth = layoutContext.getArea().getBBox().getWidth();
    int contentLength = content.length();
    int leftChar = 0;
    int rightChar = contentLength - 1;
    availableWidth -= bf.getWidth("...", 12);
    while (leftChar  0)
        availableWidth -= bf.getWidth(content.charAt(rightChar), 12);
        if (availableWidth > 0)
    String newContent = content.substring(0, leftChar) + "..." + content.substring(rightChar);
    Paragraph p = new Paragraph(newContent);
    IRenderer pr = p.createRendererSubTree().setParent(this);
    return super.layout(layoutContext);

Here it is! If you apply this renderer for a single cell (let it be D2), see what happens:

Truncated text

Truncated text

We can get the occupied area using layoutContext.getArea().getBBox() method and customize the piece of text we want to appear depending on the font size (12 in this example).

Click How to truncate text within a bounding box? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.