简体   繁体   中英

Calculate the width of a table in iText 7

I use iText 7 with html2pdf 2.1.2 version and try to convert HTML file to PDF.

I use HtmlConverter#convertToElements to process an html file. Then I would like to calculate the width of one of the elements (a table in particular).

I have tried to implement custom TagWorker class, but i get table only after it's filled.

Also tried convertToDocument and some other ways but with no success.

Is there a way to get a table width at run time?

Thanks in advance.

The bad news: in general, it's not possible to get the real width of the table until it has been placed. It highly depends on the layout area.

The good news: one can simulate table's layout and check the occupied place:

    Rectangle area = new Rectangle(0, 0, 500, 500);
    LayoutResult result = table.createRendererSubTree().setParent(doc.getRenderer()).layout(new LayoutContext(new LayoutArea(0, area)));
    Rectangle tableArea = result.getOccupiedArea().getBBox();

In the code above, I've created a renderer for the table ( createRendererSubTree() ), set its parent ( setParent(doc.getRenderer()) - this line is important for correct properties processing) and layouted it ( layout(new LayoutContext(new LayoutArea(0, area))) ;

UPD: I've read your initial question and have another solution for you. Suppose that you don't have any area to place, but want to see how much space the table could occupy.

Use the next snippet then:

MinMaxWidth minMaxWidth = ((TableRenderer)table.createRendererSubTree().setParent(doc.getRenderer())).getMinMaxWidth();
float minWidth = minMaxWidth.getMinWidth();
float maxWidth = minMaxWidth.getMaxWidth();

In the code above I've calculated the min and the max width of the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM