CSS实现自动分页打印同时每页保留重复的自定义内容

当需要打印的内容过长时系统会产生自动分割页面,造成样式不太美观。使用CSS的 @media print 结合 <table> 可以实现对分页样式的可控。效果如下:

假设有50条数据,打印时系统会自动分成两页,同时每页保留自定义的header和footer。

第一页
第二页

代码如下:

<html>
<head>
  <title>print</title>
  <style>
    /* 在打印时应用此规则 */
    @media print {
      
      
      @page {
      
      
        /* 文档的页面大小 */
        size: A4;
        /* 文档的页边距 */
        margin: 10mm 20mm 20mm;
      }

      table {
      
      
        width: 100%;
        border-collapse: collapse;
      }

      tbody tr td {
      
      
        padding-left: 5px;
        border: 1px solid #000;
        word-break: keep-all;
        font-size: .9rem;
      }

      .header-row th {
      
      
        border: 1px solid #000;
      }

      .title {
      
      
        margin: 0 0 20px;
        font-size: 1.5rem;
      }

      .footer-row {
      
      
        padding-top: 10px;
      }
    }
  </style>
</head>
<body>
	<table>
  	<thead>
      <tr>
        <th colspan="3">
          <div class="title">标题1标题1</div>
        </th>
      </tr>
      <tr class="header-row">
        <th>First Name</th>
        <th>Last Name</th>
        <th>age</th>
      </tr>
    </thead>
    <tbody id="tbody"></tbody>
    <tfoot>
      <tr>
        <td colspan="1" class="footer-row">
          <div>打印人:小王</div>
        </td>
        <td colspan="2" class="footer-row">
          <div class="footer-time">打印时间:2000-01-01 00:00:00</div>
        </td>
      </tr>
    </tfoot>
  </table>
  
  <script>
    // mock
    const rowNum = 50;
    const fragment = document.createDocumentFragment();
    for (let i = 0; i < rowNum; i++) {
      
      
      const _tr = document.createElement('tr');
      const _td1 = document.createElement('td');
      const _td2 = document.createElement('td');
      const _td3 = document.createElement('td');
      _td1.appendChild(document.createTextNode(`John${ 
        i}`));
      _td2.appendChild(document.createTextNode(`Doe${ 
        i}`));
      _td3.appendChild(document.createTextNode(`${ 
        i}`));
      _tr.appendChild(_td1);
      _tr.appendChild(_td2);
      _tr.appendChild(_td3);
      fragment.appendChild(_tr);
    }
    document.querySelector('#tbody').appendChild(fragment);
  </script>
</body>
</html>

ctrl+p / command+p 唤起打印即可查看效果

注:不能使用 @page 规则修改所有的css属性,只能修改文档的 margin、orphans、windows 和分页符,对其他属性的修改无效。@page

猜你喜欢

转载自blog.csdn.net/yotcap/article/details/129743573