我可以按如下方式设置新段落的宽度,这会产生一定的高度:
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文件期间会计算渲染高度。但我需要在最终渲染之前的高度。我怎样才能最有效地获得它?
答案 0 :(得分:9)
要获得段落的有效宽度,就像它已经在页面上绘制一样,您需要从模型元素树创建渲染器树,然后布局最顶层的渲染器。这是在代码中完成的:
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:
p.setMargin(0);