7

I'm trying to show the number of pages on PDF file.

So in the header I put this css:

.page-number:after { 
  counter-increment: pages; 
  content: counter(page) " of " counter(pages); 
 }

Html:

<span class="page-number">Page </span>

But it returns me Page 1 of 1 ... Page 2 of 2. The first counter works fine but the total is wrong. How can I solve that?

tzi
  • 7,629
  • 1
  • 21
  • 43
user3242861
  • 1,669
  • 10
  • 41
  • 82
  • Ok I don't know what is my total number of pages. Could be 4, 5,6... @Pete – user3242861 Mar 16 '18 at 09:42
  • 2
    https://stackoverflow.com/questions/46711147/css-page-x-of-y-for-media-print: _“The obsolete method is that there used to be an automatically instantiated CSS counter named `pages`”_ .. according to this, such a `pages` counter doesn’t exist any more in current version of CSS counters. I don’t think what you want is possible using CSS alone. – CBroe Mar 16 '18 at 09:43
  • I am facing this same issue and i dont think so we can get the total number of pages . i am also getting 1 of 1 and 2 of 2 – Bhupinder kumar Jun 22 '18 at 09:42
  • see https://print-css.rocks/lesson-page-numbers.html – mb21 Jan 14 '19 at 11:15

2 Answers2

7

There is no way to get a counter total with CSS counters so the only way I can think of getting the output you require is to duplicate the HTML (which may not be a big problem if the content is dynamically generated). Output the HTML once to get the total number of pages then again to get the current page.

#pageCounter {
  counter-reset: pageTotal;
}
#pageCounter span {
  counter-increment: pageTotal; 
}
#pageNumbers {
  counter-reset: currentPage;
}
#pageNumbers div:before { 
  counter-increment: currentPage; 
  content: "Page " counter(currentPage) " of "; 
}
#pageNumbers div:after { 
  content: counter(pageTotal); 
}
<div id="pageCounter">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>
<div id="pageNumbers">
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
</div>
Hidden Hobbes
  • 13,299
  • 3
  • 33
  • 60
  • Its good solution but if you will page the pageNumber above the pageCounter it will not work – Bhupinder kumar Jun 22 '18 at 09:53
  • @Bhupinderkumar Yes, for this to work it is integral that `#pageCounter` is before `#pageNumbers`. If it is after the `pageTotal` counter will not have been incremented by the time it is displayed on the screen. – Hidden Hobbes Jun 22 '18 at 10:05
-2

.page{
counter-reset: page;
}
.page .page-number{
  display:block;
  }
.page .page-number:after{
counter-increment: page;
content:counter(page);
}
.page:after{
    display: block;
    content: "Number of pages: " counter(page);
}
<div class="page">
<span class="page-number">Page </span>
<span class="page-number">Page </span>
<span class="page-number">Page </span>
<span class="page-number">Page </span>
</div>
Pushparaj
  • 1,034
  • 8
  • 26