When I call
setFixedHeight() on a
PdfPCell, and add more text than fits in the given height, iText seems to print the prefix of the string which fits.
Can I control this clipping algorithm? For example:
- Print a suffix of the string rather than a prefix.
- Mark a substring of the string as not to be removed. This is with footnote references. If I add text saying "Hello World ", the  is a reference to a footnote and should not be removed. It's okay to remove the other characters of the string, like "World".
- When there are multiple words in the string, iText seems to eliminate a word that doesn't fit, while I would like it partially printed. That is, if the string is "Hello World", and the cell has room only for "Hello Wo...", I would like that to be printed, rather than just "Hello", as iText prints.
- Rather than printing characters in their entirety, print only part of them. Imagine printing the text to a PNG and chopping off the top and/or bottom part of the PNG to fit it in the space available. For example, notice that the top line and the bottom line are partially clipped here:
Are any of these possible? Does iText give me any control over how text is clipped? Thanks.
I have written a proof of concept, ClipCenterCellContent, where we try to fit the text
"D2 is a cell with more content than we can fit into the cell." in a cell that is too small.
Just like in your other question "How do I get the rendered dimensions of text?", we add the content using a cell event, but we now add it twice: once in simulation mode (to find out how much space is needed vertically) and once for real (using an offset).
This adds the content in simulation mode (we use the width of the cell and an arbitrary height):
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS]; ColumnText ct = new ColumnText(canvas); ct.setSimpleColumn(new Rectangle(0, 0, position.getWidth(), -1000)); ct.addElement(content); ct.go(true); float spaceneeded = 0 - ct.getYLine(); System.out.println(String.format( "The content requires %s pt whereas the height is %s pt.", spaceneeded, position.getHeight()));
We now know the needed height and we can add the content for real using an offset:
float offset = (position.getHeight() - spaceneeded) / 2; System.out.println(String.format( "The difference is %s pt; we'll need an offset of %s pt.", -2f * offset, offset)); PdfTemplate tmp = canvas.createTemplate( position.getWidth(), position.getHeight()); ct = new ColumnText(tmp); ct.setSimpleColumn(0, offset, position.getWidth(), offset + spaceneeded); ct.addElement(content); ct.go(); canvas.addTemplate(tmp, position.getLeft(), position.getBottom());
In this case, I used a
PdfTemplate to clip the content.