'How to modify the first pageNumber or execute JS in header or footer template with Chrome DevTools Protocol's printToPDF

I'm using Headless Chrome to print out PDF files by using the printToPDF CDP method. If we set displayHeaderFooter parameter to true, then we can set specific page header and footer by using the parameters headerTemplate and footerTemplate. The protocol provides some HTML classes to display some information, these are: date, title, url, pageNumber, totalPages.

For example, we can set footerTemplate to <span class="pageNumber"></span> to display the current page number in the footer. We also need to add some style to display it properly. The default header and footer settings can be found here, and the renderer C++ component is here.

I would like to modify the displayed pageNumber values. My goal is to count pages from a given number.

The Puppeteer API documentation note that headerTemplate and footerTemplate markup have the following limitations:

  1. Script tags inside templates are not evaluated.
  2. Page styles are not visible inside templates.

A GitHub comment provides the following:

<div style="font-size: 10px;">
  <div id="test">header test</div>
  <img src='http://www.chromium.org/_/rsrc/1438879449147/config/customLogo.gif?revision=3' onload='document.getElementById("test").style.color = "green";this.parentNode.removeChild(this);'/>
</div>

It says, if we use an onload attribute on an img tag, then we can run JavaScript in the templates. However, I was not able to reproduce the result, what is shown on the screenshot under the snipplet.

For example, the following JavaScript could count pages from 10:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="tmpimg" 
onload="var x = document.getElementById('pn').innerHTML; var y = 10; document.getElementById('pn').innerHTML = parseInt(x) + y; this.parentNode.removeChild(this);"/>
<span id="pn" class="pageNumber"></span>

But unfortunately this script does not modify the page numbering, and I have no idea how to solve this problem. I've also tried to use pure CSS solutions, but without success.

Any ideas are welcome to resolve this issue.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source