How to truncate text within a bounding box?
I am writing content to a PdfContentByte
object directly using:
PdfContentByte.showTextAligned();
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)
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
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.