The most upvoted answer did not work for me, the footer only showed on the last page. (This behavior is also mentioned in the comments below the answer provided by Daniel Kaplan.)
The solution to this problem was provided by the following comment:
@PauloOliveira It shows only on the last page when the is too far down in the . Place it somewhere higher so that it will print before the first page ends. But John Mark's answer is better. – Edward Feb 3 '20 at 12:16
So what has worked for me (using FlyingSaucer rendering with OpenPDF) is the following - placing the definition of the footer element somewhere above the main content and applying the solution provided by 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>
And the CSS code:
@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);
}