iText 7: Paragraph height as it would be rendered

☆樱花仙子☆ 提交于 2019-12-21 05:24:08

问题


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);


来源:https://stackoverflow.com/questions/49598325/itext-7-paragraph-height-as-it-would-be-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!