我有一个项目,需要打印一个有很多行的HTML表。

我的问题是表格打印多页的方式。它有时会把一行切成两半,使它无法阅读,因为一半在一页的流血边缘,剩下的打印在下一页的顶部。

我能想到的唯一可行的解决方案是使用堆叠的div而不是一个表,并在需要时强制换页。但在经历整个变化之前,我想我可以在这里问一下。


当前回答

我最近用一个很好的解决方案解决了这个问题。

CSS:

.avoidBreak { 
    border: 2px solid;
    page-break-inside:avoid;
}

JS:

function Print(){
    $(".tableToPrint td, .tableToPrint th").each(function(){ $(this).css("width",  $(this).width() + "px")  });
    $(".tableToPrint tr").wrap("<div class='avoidBreak'></div>");
    window.print();
}

效果好极了!

其他回答

接受的答案在所有浏览器中都不适用,但以下css确实适用于我:

tr    
{ 
  display: table-row-group;
  page-break-inside:avoid; 
  page-break-after:auto;
}

html的结构是:

<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
    <tr></tr>
    ...
  </tbody>
</table>

在我的例子中,有一些附加的问题与头tr,但这解决了原来的问题,保持表行中断。

由于标题的问题,我最终以:

#theTable td *
{
  page-break-inside:avoid;
}

这并没有阻止行断裂;只是每个单元格的内容。

注意:当使用page-break-after:always for标签时,它将在表的最后一位之后创建一个分页符,每次都在末尾创建一个完全空白的页面! 要解决这个问题,只需将其更改为page-break-after:auto。 它将正确地断开,不会创建额外的空白页。

<html>
<head>
<style>
@media print
{
  table { page-break-after:auto }
  tr    { page-break-inside:avoid; page-break-after:auto }
  td    { page-break-inside:avoid; page-break-after:auto }
  thead { display:table-header-group }
  tfoot { display:table-footer-group }
}
</style>
</head>

<body>
....
</body>
</html>

我已经尝试了上面给出的所有建议,并为这个问题找到了简单而有效的跨浏览器解决方案。此解决方案不需要样式或分页符。对于解决方案,表格的格式应该是:

<table>
    <thead>  <!-- there should be <thead> tag-->
        <td>Heading</td> <!--//inside <thead> should be <td> it should not be <th>-->
    </thead>
    <tbody><!---<tbody>also must-->
        <tr>
            <td>data</td>
        </tr>
        <!--100 more rows-->
    </tbody>
</table>

以上格式已测试并可在跨浏览器中工作

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tbody>
        <tr>
            <td>x</td>
        </tr>
        <tr>
            <td>x</td>
        </tr>
        <!-- 500 more rows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>

使用这些CSS属性:

page-break-after

page-break-before 

例如:

<html>
<head>
<style>
@media print
{
table {page-break-after:always}
}
</style>
</head>

<body>
....
</body>
</html>

via