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

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

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


当前回答

我面对同样的问题,到处寻找解决方案,最后,我找到了适合我的所有浏览器的解决方案。

html {
height: 0;
}

使用这个css或代替css,你可以有这个javascript

$("html").height(0);

希望这对你也有用。

其他回答

好男人……上面的大多数解都没用。这就是我的工作方式。

HTML

<table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>

第一组头部被用作一个假的,这样就不会有一个丢失的顶部边界在第二个头部(即。原始页头),而分页。

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

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();
}

效果好极了!

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

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

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

使用这些CSS属性:

page-break-after

page-break-before 

例如:

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

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

via

我最终遵循了@vicenteherrera的方法,并进行了一些调整(可能是针对引导程序的)。

基本上;我们不能破坏trs或TDS,因为它们不是块级元素。因此,我们将div嵌入到每个div中,并对div应用我们的分页-*规则。我们在每个div的顶部添加了一些填充,以补偿任何样式构件。

<style>
    @media print {
        /* avoid cutting tr's in half */
        th div, td div {
            margin-top:-8px;
            padding-top:8px;
            page-break-inside:avoid;
        }
    }
</style>
<script>
    $(document).ready(function(){
        // Wrap each tr and td's content within a div
        // (todo: add logic so we only do this when printing)
        $("table tbody th, table tbody td").wrapInner("<div></div>");
    })
</script>

边际和填充调整是必要的,以抵消某种类型的抖动,这是引入(我的猜测-从bootstrap)。我不确定我是否提出了这个问题的其他答案的新解决方案,但我想这可能会帮助到一些人。