Search code examples
javaitextwidthitext7paragraph

iText7: How to get the real width of a Paragraph


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?


Solution

  • 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.