Search code examples
c#htmlpdfitextitext7

itext7 HTML to PDF ignores column widths


I'm using iText7's pdfHtml add-on to convert an HTML table into a PDF. However I cannot get it to obey the defined column widths.

I'm using the HtmlConverter.ConvertToDocument to convert my HTML into a PDF.

This is my table:

table {
  border-collapse: collapse;
}

table,
td,
th {
  border: 1px solid black;
}

.gray-header {
  background-color: lightgray;
}
<table style="table-layout: fixed; width: 700px;">
  <thead>
    <tr class="gray-header">
      <th rowspan="2" style="width: 50px;">A</th>
      <th rowspan="2" style="width: 250px;">B</th>
      <th colspan="4" style="width: 400px;">COLSPAN</th>
    </tr>
    <tr class="gray-header">
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
      <td>D</td>
      <td>F</td>
      <td>G</td>
    </tr>
  </tbody>
</table>

This is the table in the PDF

enter image description here

The columns A and B are the same width. B should be 5 times larger then A.


Solution

  • The workaround is to specify column width definitions in <col> tags located in <colgroup>:

    <table style="table-layout: fixed; width: 700px;">
      <colgroup>
        <col style="width: 50px;"/>
        <col style="width: 250px;"/>
        <col/>
        <col/>
        <col/>
        <col/>
      </colgroup>
      <thead>
      <tr class="gray-header">
        <th rowspan="2">A</th>
        <th rowspan="2">B</th>
        <th colspan="4">COLSPAN</th>
      </tr>
      <tr class="gray-header">
        <th>C</th>
        <th>D</th>
        <th>E</th>
        <th>F</th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
        <td>F</td>
        <td>G</td>
      </tr>
      </tbody>
    </table>

    Visual PDF result for the table structure above:

    result