How to truncate text within a bounding box?

Tags: tablesiText 7

I am writing content to a PdfContentByte object directly using:

PdfContentByte.showTextAligned();
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 < contentLength && rightChar != leftChar) {
        availableWidth -= bf.getWidth(content.charAt(leftChar), 12);
        if (availableWidth > 0)
            leftChar++;
        else
            break;
        availableWidth -= bf.getWidth(content.charAt(rightChar), 12);
        if (availableWidth > 0)
            rightChar--;
        else
            break;
    }
    String newContent = content.substring(0, leftChar) + "..." + content.substring(rightChar);
    Paragraph p = new Paragraph(newContent);
    IRenderer pr = p.createRendererSubTree().setParent(this);
    this.childRenderers.add(pr);
    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 peace of text we want to appear depending on the font size (12 in this example).

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