2

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?

bardosy
  • 73
  • 7
  • Currently I use a far-from-ideal workaround: PdfFont has a .getWidth(string, fontsize) function, but it ignores the difference between normal, bold and italic style. (And the width of a bold text is longer then the same text in normal.) So I still wait for the good solution. – bardosy May 21 '20 at 06:37

1 Answers1

3

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.

bardosy
  • 73
  • 7