设置 Table 列宽小于内容

Set Table Column Width Less Than Content

我在 Java 代码中使用 Flying Saucer PDF 生成库将 HTML 模板转换为 PDF。该模板由具有固定列数的 table 组成。我希望每一列都具有固定的宽度,并且其中的内容在溢出时隐藏。我为任务写了以下 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;
}
td, th {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

显然,如果内容超出列宽,这不会限制列宽。该模板在 Chrome 和 Firefox 中看起来不错,但在生成的 PDF 中却不行。

有没有办法用 Flying Saucer PDF 限制每列的宽度?

您可以将以下样式添加到 table 中:table-layout:fixed.

示例:

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