itextxmlworker

Center a table horizontally with iText's XMLWorker


I've tried centering a table in two ways:

Attempt 1 code:

<h1>Attempt 1</h1>

<table style="width: 50%; margin: 0 auto;">
    <tr>
        <th>foo</th>
        <td>bar</td>
    </tr>
    <tr>
        <th>foo</th>
        <td>bar</td>
    </tr>
</table>

Attempt 2 code:

<h1>Attempt 2</h1>

<table style="width: 50%;" align="center">
    <tr>
        <th>foo</th>
        <td>bar</td>
    </tr>
    <tr>
        <th>foo</th>
        <td>bar</td>
    </tr>
</table>

Using the XMLWorker demo: http://demo.itextsupport.com/xmlworker/

This is the HTML preview:

html preview

As you can see, both tables are centered.
Although, when I click "transform", I get this:

generated pdf

I also tried later wrapping the table in a <div style="text-align: center"></div> which didn't work


Solution

  • As explained in the comment section, this isn't supported yet in XML Worker. We'll add it to the next release. If you can't wait until the next release, please apply this patch:

    diff --git a/src/main/java/com/itextpdf/tool/xml/html/table/Table.java b/src/main/java/com/itextpdf/tool/xml/html/table/Table.java
    index 541818bfc9..e262b4a406 100644
    --- a/src/main/java/com/itextpdf/tool/xml/html/table/Table.java
    +++ b/src/main/java/com/itextpdf/tool/xml/html/table/Table.java
    @@ -165,6 +165,19 @@ public class Table extends AbstractTagProcessor {
                 table.setHeaderRows(headerRows + footerRows);
                 table.setFooterRows(footerRows);
    
    +            if ( tag.getAttributes().containsKey(HTML.Attribute.ALIGN)) {
    +                String value = tag.getAttributes().get(HTML.Attribute.ALIGN);
    +                if ( value != null ) {
    +                    if (value.equalsIgnoreCase(CSS.Value.RIGHT)) {
    +                        table.setHorizontalAlignment(Element.ALIGN_RIGHT);
    +                    } else if ( value.equalsIgnoreCase(CSS.Value.LEFT)) {
    +                        table.setHorizontalAlignment(Element.ALIGN_LEFT);
    +                    } else if ( value.equalsIgnoreCase(CSS.Value.CENTER)) {
    +                        table.setHorizontalAlignment(Element.ALIGN_CENTER);
    +                    }
    +                }
    +            }
    +
                 int direction = getRunDirection(tag);
                 if (direction != PdfWriter.RUN_DIRECTION_DEFAULT) {
                     table.setRunDirection(direction);