CSS counter-increment 页面打印视图问题

CSS counter-increment page on print view issue

我在浏览器的打印视图中遇到页数计数问题。

创建按类别分隔 table 的报告我需要按类别重置计数器,当我们创建长数据 table 且行数不确定时,我们无法计算有多少行table header 的显示次数,以确定有多少页将包含该类别。

有没有办法在打印视图中计算 header 将显示多少次?

JSFiddle

https://jsfiddle.net/7prs03eh/3/

.report-table {
  page-break-after: always;
  counter-reset: page;
}

.report-header {
  display: table-header-group;
}

.report-header tr th span.page-number:after {
  counter-increment: page;
  content: "Pag:" counter(page);
}

.report-footer {
  display: table-footer-group;
}
<button onclick="window.print();">Print</button>
<table class="report-table">
  <thead class="report-header">
    <tr colspan="3"> Category 1 </tr>
    <tr>
      <th>content</th>
      <th>content</th>
      <th><span class="page-number"></span></th>
    </tr>
  </thead>
  <tfoot class="report-footer">
    <tr>
      <td></td>
      <td>total</td>
      <td>$ 0,00 </td>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>long</td>
      <td>data</td>
      <td>here</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
  </tbody>
</table>

<table class="report-table">
  <thead class="report-header">
    <tr colspan="3"> Category 2 </tr>
    <tr>
      <th>content</th>
      <th>content</th>
      <th><span class="page-number"></span></th>
    </tr>
  </thead>
  <tfoot class="report-footer">
    <tr>
      <td></td>
      <td>total</td>
      <td>$ 0,00 </td>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
    <tr>
      <td>long</td>
      <td>data</td>
      <td>here</td>
    </tr>
    <tr>
      <td>content</td>
      <td>content</td>
      <td>content</td>
    </tr>
  </tbody>
</table>

恐怕 css 添加计数打印数字是 不可能的

如果 Firefox 是一个选项,您可能会解决这个问题 MDN notes:

Using CSS counter to print page numbers only works on Firefox. It’s unclear if the behavior is defined in the specification and whether or not it would be supported in other browsers at all. See issue filed with Chromium.

#print-foot:after {
    content: counter(page);
    counter-increment: page;
  }

查看完整内容 code snippet in JSFiddle

请记住,虽然在 Firefox 中可行,但此功能将被视为 extremely buggy,并且很难进行进一步的自定义和样式设置。此功能在浏览器内打印中是不可能的。

如果服务器端 PDF 生成是一个选项,那么有几个库可以为您工作,例如PDFjs, Prince 等等。