Search code examples
htmlcsspdfflying-saucer

Set Table Column Width Less Than Content


I'm using Flying Saucer PDF generation library in my Java code to convert an HTML template into PDF. The template consists of a table with fixed number of columns. I want each column to have a fixed width and the content in it to hide on overflow. I wrote the following CSS for the task -

.col1 {
    width: 50px;
    max-width: 50px;
    min-width: 50px;
}
.col2 {
    width: 70px;
    max-width: 70px;
    min-width: 70px;
}
.col3 {
    width: 120px;
    max-width: 120px;
    min-width: 120px;
}
td, th {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Apparently this doesn't restrict the column width if content grows above it. The template looks fine in Chrome and Firefox but not in the generated PDF.

Is there a way to restrict each column's width with Flying Saucer PDF?


Solution

  • You can add the following style to the table : table-layout:fixed.

    Example:

    <html>
        <head>
            <style type="text/css">
                .col1 {width: 50px;max-width:50px;min-width: 50px;}
                .col2 {width: 70px;max-width: 70px;min-width: 70px;}
                .col3 {width: 120px;max-width: 120px;min-width: 120px;}
                table{table-layout:fixed;}  
                td, th {
                    border:1px solid red
                    overflow: hidden;
                    white-space: nowrap;
                }
        </style>
        </head>
        <body>
          <table >
            <thead>
              <tr>
                <td class="col1">Col1</td>
                <td class="col2">Col2</td>
                <td class="col3">Col3</td>
              </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="col1">Lorem ipsum dolor sit amet, consectetur </td>
                    <td class="col2">la, molestie vel diam vitae, bibendum consequat enim. </td>
                    <td class="col3">s non metus. Donec auctor ipsum in quam bibendum, sit a</td>
                </tr>
            </tbody>
          </table>
        </body>
    </html>