iText7: How to get the real width of a Paragraph

为君一笑 提交于 2021-01-28 09:13:57

问题


I need to know the width (in point) of a Paragraph before add to the document. I searched here and found Alexey answer about Paragraph's height. So I made it with width, but it doesn't work. Always return the Rectangle's width no matter how long the Paragraph. I tried this code:

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

So, my question is, what is wrong with this code if it works with height, but not with width?


回答1:


A friend of mine solved it. The last line of the code should be this one:

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

It result the correct value.



来源:https://stackoverflow.com/questions/61911094/itext7-how-to-get-the-real-width-of-a-paragraph

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