Repeating table headers in PDF downloads using headless chrome

By berliner, 24 April, 2019

tl;drFor repeating table headers across pages when creating PDFs with puppeteer and headless chrome, use thead and these CSS declarations:

thead {
  display: table-header-group;
  break-inside: avoid;

Full storyHeadless chrome and puppeteer are great tools to create stunning PDFs programatically. I use it a lot recently and there are not a lot of issues that I had to work around (custom fonts and styles in the PDF header being one, but that's solvable).But recently I was tasked with assuring nice page breaks for long tables and to make sure that the table headers would repeat on new pages. The internet told me that I should be good if I used thead elements. But that didn't work. Also adding display: table-header-group; to the thead elements didn't do the trick.After more research, I found 2 bug issues regarding this, one for webkit and one for chromium. Documentation about this is kind of sparse, but reading through those issues and some referenced issues, I finally got it working.The key to success was mentioned in this commit for the chromium project: 81c0fc:

Display table header groups at the top of each pageFF, IE and Edge all repeat a table header group at the top of each printed page.This area is underspecified but after some discussion in the bug we agreed to repeat the header group if it has break-inside:avoid. We make this the default style for theads when printing.

So I added break-inside:avoid to the thead element in my table and voilĂ , it worked.