iText7:如何获取段落的实际宽度
iText7: How to get the real width of a Paragraph
在添加到文档之前,我需要知道段落的宽度(磅)。我在这里搜索并找到了关于段落高度的 Alexey 回答。所以我用宽度做了它,但它不起作用。无论段落多长,始终 return 矩形的宽度。
我试过这段代码:
private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
// Create renderer tree
IRenderer paragraphRenderer = paragraph.createRendererSubTree();
// Do not forget setParent(). Set the dimensions of the viewport as needed
LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
// LayoutResult#getOccupiedArea() contains the information you need
return result.getOccupiedArea().getBBox().getWidth();
}
所以,我的问题是,如果这段代码适用于高度,但不适用于宽度,那么它有什么问题?
我的一个朋友解决了它。代码的最后一行应该是这一行:
private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
// Create renderer tree
IRenderer paragraphRenderer = paragraph.createRendererSubTree();
// Do not forget setParent(). Set the dimensions of the viewport as needed
LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
// LayoutResult#getOccupiedArea() contains the information you need
//return result.getOccupiedArea().getBBox().getWidth();
return ((ParagraphRenderer) paragraphRenderer).getMinMaxWidth().getMaxWidth();
}
结果正确。
在添加到文档之前,我需要知道段落的宽度(磅)。我在这里搜索并找到了关于段落高度的 Alexey 回答。所以我用宽度做了它,但它不起作用。无论段落多长,始终 return 矩形的宽度。 我试过这段代码:
private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
// Create renderer tree
IRenderer paragraphRenderer = paragraph.createRendererSubTree();
// Do not forget setParent(). Set the dimensions of the viewport as needed
LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
// LayoutResult#getOccupiedArea() contains the information you need
return result.getOccupiedArea().getBBox().getWidth();
}
所以,我的问题是,如果这段代码适用于高度,但不适用于宽度,那么它有什么问题?
我的一个朋友解决了它。代码的最后一行应该是这一行:
private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
// Create renderer tree
IRenderer paragraphRenderer = paragraph.createRendererSubTree();
// Do not forget setParent(). Set the dimensions of the viewport as needed
LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
// LayoutResult#getOccupiedArea() contains the information you need
//return result.getOccupiedArea().getBBox().getWidth();
return ((ParagraphRenderer) paragraphRenderer).getMinMaxWidth().getMaxWidth();
}
结果正确。