当须要打印的内容过长时零碎会产生主动宰割页面,造成款式不太好看。应用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