Skip to content

Instantly share code, notes, and snippets.

@seripap
Last active January 27, 2020 09:20
Show Gist options
  • Save seripap/81241195e182b62adc3c87c27258f85f to your computer and use it in GitHub Desktop.
Save seripap/81241195e182b62adc3c87c27258f85f to your computer and use it in GitHub Desktop.
Chrome Headless PDF with Page Numbers

Getting page numbers using Chrome Headless

This is a small hack that adds a page numbers at the bottom of the page. Using Puppeteer and a fixed height, the page will render at an A4 size via web and have a fixed footer.

await page.goto('https://bl.ocks.org/seripap/raw/81241195e182b62adc3c87c27258f85f/', {waitUntil: 'networkidle'});
await page.pdf({
  path: 'hacks.pdf',
  format: 'A4'
});
<link rel="stylesheet" type="text/css" href="https://necolas.github.io/normalize.css/7.0.0/normalize.css">
<style>
.page {
height: 1122px;
display: flex;
flex-direction: column;
}
.page-extend {
flex-grow: 1;
}
.page-footer {
text-align: right;
}
</style>
<div class="page">
<div class="page-contents">
<h1>
Hello World
</h1>
</div>
<div class="page-extend"></div>
<div class="page-footer">
<div class="js-page-number"></div>
</div>
</div>
<div class="page">
<div class="page-contents">
<h1>
Hello World 2
</h1>
</div>
<div class="page-extend"></div>
<div class="page-footer">
<div class="js-page-number"></div>
</div>
</div>
<div class="page">
<div class="page-contents">
<h1>
Hello World 3
</h1>
</div>
<div class="page-extend"></div>
<div class="page-footer">
<div class="js-page-number"></div>
</div>
</div>
<script>
(function() {
let pageCounter = 1;
const eles = document.getElementsByClassName('js-page-number')
const pages = Array.prototype.slice.call( eles )
pages.forEach((page) => {
console.log(page)
page.innerHTML = pageCounter;
pageCounter++;
})
})()
</script>
@lygaret
Copy link

lygaret commented Feb 2, 2018

I wonder if you could do it with display: grid flow...

@nitinja
Copy link

nitinja commented Nov 1, 2019

Impressive solution! Wont work for dynamic content of unknown height though.

@odykyi
Copy link

odykyi commented Jan 27, 2020

Hey!

use attribute footerTemplate with displayHeaderFooter for show pages originally using puppeteer API

await page.pdf({
  path: 'hacks.pdf',
  format: 'A4',
  displayHeaderFooter: true,
  footerTemplate: '<div><div class='pageNumber'></div> <div>/</div><div class='totalPages'></div></div>'
});

https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagepdfoptions

// footerTemplate HTML template for the print footer.
// Should be valid HTML markup with following CSS classes used to inject printing values into them:
// - date formatted print date
// - title document title
// - url document location
// - pageNumber current page number
// - totalPages total pages in the document

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment