7

I can set the width of a new paragraph as follows, which results in a certain height:

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

Of course p.getHeight() is null, since the rendered height is calculated during rendering the PDF file. But I need the height before the final rendering. How can I get it most efficiently?

ideaboxer
  • 3,863
  • 8
  • 43
  • 62
  • 1
    I would say Alexey is both credible and official. After all, he is one of the developers of iText 7. Furthermore, you have to layout the paragraph to determine its eventual height. I might have proposed rendering to some throw-away Canvas but his solution is better. So you might probably describe what you hope for in an alternative answer. – mkl Apr 04 '18 at 06:49
  • Since I am not sure what is the best-practice, I do not know which answer I should expect. Usually the community comes up with more than one solution. Thus I am usually waiting some days. – ideaboxer Apr 04 '18 at 16:38
  • Don't hold your breath waiting for a better solution ;) – mkl Apr 04 '18 at 18:00
  • I just don't like being overhasty. Slow and steady wins the race. – ideaboxer Apr 04 '18 at 18:22

1 Answers1

20

To get the effective width of the paragraph as if it was drawn on a page already, you need to create renderer tree from model element tree, and then layout the topmost renderer. This is how it's done in code:

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

Please note that the computed dimensions will also include margins (present in a paragraph by default), so if you want to get the height without margins you should first set paragraph margin to 0:

p.setMargin(0);
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
  • 1
    @ideaboxer great! Please accept the answer then so that other visitors can easily see that the answer solves the problem. – Alexey Subach Apr 01 '18 at 18:46
  • I would like to give other users a chance to post their ideas. But I will not forget to finally accept an answer! – ideaboxer Apr 01 '18 at 21:36
  • How would you do it to to get the width instead of the height ? With this method I always get the width of the Rectangle specified in the LayoutArea. – MHogge Jul 06 '20 at 07:39
  • @MHogge That is because the width is already fixed in the second line of the code (`p.setWidth(100);`). – Jules Oct 13 '20 at 07:56