iText 7:将呈现的段落高度 [英] iText 7: Paragraph height as it would be rendered
问题描述
我可以设置新段落的宽度,如下所示,这会产生一定的高度:
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);
当然 p.getHeight()
是 null
,因为渲染高度是在渲染PDF文件期间计算的。但是我需要在最终渲染之前的高度。我怎样才能最有效地获得它?
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?
推荐答案
获取段落的有效宽度,就像它已经在页面上绘制一样,您需要从模型元素树创建渲染器树,然后布局最顶层的渲染器。这是在代码中完成的方式:
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());
请注意,计算出的尺寸也将包括边距(默认情况下显示在一个段落中),所以如果如果你想获得没有边距的高度,首先应将段落边距设置为0:
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);
这篇关于iText 7:将呈现的段落高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!