29

我花了更多的研究而不是自己想弄清楚,所以我将在这里发布一个全面的答案。看起来这样做的信息分布在许多不同的网站上,我想把它放在一个地方。 这个答案 可能是一样的,但我的眼睛呆滞了,因为它是在 Java 字符串中而不是在 html 模板中。这是问题:

我正在渲染 PDF,我希望页面底部有一个页脚,上面写着“第 n 页,共 m 页”,其中“n”是您所在的页码,“m”是文档中的总页数。我怎么做?

4

5 回答 5

39

在您的 html 中,您需要将其放在body标签中的某个位置:

<div id="footer">
    page <span id="pagenumber"></span> of <span id="pagecount"></span>
</div>

这应该是您的 css/样式:

    #footer {
        position: running(footer);
        text-align: right;
    }

    @page {
        @bottom-right {
            content: element(footer);
        }
    }

    #pagenumber:before {
        content: counter(page);
    }

    #pagecount:before {
        content: counter(pages);
    }

您可以在此处了解有关该@bottom-right选项的更多信息。

于 2013-07-30T17:44:54.307 回答
36

您还可以尝试更简洁的方法:

@page {
  @bottom-right {
    content: "Page " counter(page) " of " counter(pages);
  }
}

您需要将它放在您的 css/style 中,并且不需要添加额外的页脚 HTML 元素。

于 2014-12-19T13:59:15.943 回答
3

@John Mark 的解决方案对我有用。在我的应用程序中,我需要在 HTML 中嵌入样式信息,因此我将其包装在<style>标签中并将其放在<head>before<title>中。也许这些信息对其他人有用。

于 2015-09-11T13:33:30.543 回答
3

重要错误和解决方案!

对于初学者来说,使用以下 John Mark 的解决方案是使其正常工作的正确方法:

@page {
  @bottom-right {
    content: "Page " counter(page) " of " counter(pages);
  }
}

但是,很多人可能会遇到以下问题,您的PDF 已停止生成!

这可以通过更新您的飞碟版本来解决。

当我的 PDF 由于@page 和 @bottom-right css 代码而停止生成时,我正在运行9.1.4 。

这是飞碟中的一个故障,已在9.1.5版本中修复!

确保更新到9.1.5并使用 John Mark 的答案。

于 2018-11-29T15:15:24.957 回答
1

最受好评的答案对我不起作用,页脚只显示在最后一页。(在 Daniel Kaplan 提供的答案下方的评论中也提到了这种行为。)

以下评论提供了此问题的解决方案:

@PauloOliveira 它仅在 . 将它放在更高的地方,以便在第一页结束之前打印。但约翰马克的答案更好。– 爱德华 2020 年 2 月 3 日 12:16

所以对我有用的(使用 OpenPDF 的 FlyingSaucer 渲染)如下 - 将页脚元素的定义放在主要内容上方的某个位置并应用 Daniel Kaplan 提供的解决方案:

<body>
  <div id="header">Some header content</div>
  <div id="footer">
    page <span id="pagenumber"></span> of <span id="pagecount"></span>
  </div>
  <div th:each="item: ${listOfItems}">
    [The long content listing things over multiple pages...]
  </div>
</body>

和CSS代码:

@page {
    size: A4 portrait;
    margin-top: 2cm;
    margin-left: 2cm;
    margin-right: 2cm;
    margin-bottom: 3cm;

    @bottom-left {
        content: element(footer); /* footer element must be specified before end of first page! */
        vertical-align: top;
    }
}


#pagecount::after {
    content: counter(pages);
}

#pagenumber::after {
    counter-increment: page;
    counter-reset: page 1;

    content: counter(page);
}
于 2021-10-19T14:34:49.550 回答