Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: numbering printed pages in Chrome

The browser that I have to support is Chrome (using electron for my project), so using any other browser is not an option.

I've looked for the solution to this problem for a while, it doesn't seem to have an answer to it. I've tried using this form of approach (copied from CSS page x of y for @media print):

The CSS is:

#content {
    display: table;
}

#pageFooter {
    display: table-footer-group;
}

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

And the HTML code is:

<div id="content">
  <div id="pageFooter">Page </div>
  multi-page content here...
</div>

The approach above works on FF but not on Chrome. It seems like thead/tfoot of chrome repeats on every printed page on print preview, but it doesn't results in any counter increment. The same counter value is printed on every printed page.

I also tried approaches that involve @page, but this seems to stop working a couple of years ago.

Example (copied from Browser Support for CSS Page Numbers):

@page {
    counter-increment: page;
    counter-reset: page 1;
    @top-right {
        content: "Page " counter(page) " of " counter(pages);
    }
}

Does anyone know a workaround for this problem? Or Am I dead in the water? Any javasript/nodejs solution is welcome.

like image 563
TSP Avatar asked Nov 07 '22 03:11

TSP


1 Answers

If you are looking to add page numbers when printing under Chrome/Chromium, one easy solution is to use Paged.js.

This JS library takes your HTML/CSS and cuts it into pages, ready to print as a book, that you will preview in your browser. It makes the @page and most the CSS3 specifications work for Chrome.

Solution if you are OK with cutting your view into pages, ready to print

Just add their CDN in the head tag of your page :

<link href="path/to/file/interface.css" rel="stylesheet" type="text/css">

You can then add page numbers by using the automated counter page. Example :

HTML to put anywhere you want to display the current page number:

<div class="page-number"></div>

CSS to make the number appear in the div :

.page-number{
  content: counter(page)
}

The library also allows to easily manage page margins, footers, headers, etc.

Solution if you want to show numbers (and page breaks) only when printing

In this case, you need to apply the Paged.js CDN only when printing the document. One way I can think of would be to add a print me button that fires Javascript to :

  1. add the CDN to the page
  2. and then execute window.print(); to launch the printing prompt of the navigator
like image 166
clemoun Avatar answered Nov 14 '22 23:11

clemoun