iText 7: Paragraph height as it would be rendered

2020-06-21 05:15发布

问题:

I can set the width of a new paragraph as follows, which results in a certain height:

Paragraph p = new Paragraph("some longer text some longer text some longer text");
p.setWidth(100);
System.out.println("height " + p.getHeight());
document.add(p);

Of course p.getHeight() is null, since the rendered height is calculated during rendering the PDF file. But I need the height before the final rendering. How can I get it most efficiently?

回答1:

To get the effective width of the paragraph as if it was drawn on a page already, you need to create renderer tree from model element tree, and then layout the topmost renderer. This is how it's done in code:

Paragraph p = new Paragraph("some longer text some longer text some longer text");
p.setWidth(100);

// Create renderer tree
IRenderer paragraphRenderer = p.createRendererSubTree();
// Do not forget setParent(). Set the dimensions of the viewport as needed
LayoutResult result = paragraphRenderer.setParent(document.getRenderer()).
                        layout(new LayoutContext(new LayoutArea(1, new Rectangle(100, 1000))));

// LayoutResult#getOccupiedArea() contains the information you need
System.out.println("height " + result.getOccupiedArea().getBBox().getHeight());

Please note that the computed dimensions will also include margins (present in a paragraph by default), so if you want to get the height without margins you should first set paragraph margin to 0:

p.setMargin(0);