Prevent page breaks in puppeteer pdf

2k Views Asked by At

I have html like

<table>
<tbody></tbody>
</table>

This template is getting converting to PDF with puppeteer where my tabular data is splitting across two pages however i dont want tabular data to split across the pages

I have tried all the solutions of SO for this issue https://github.com/puppeteer/puppeteer/issues/6366 but still I am not able to find the solution I have tried page-break-inside :avoid in tbody/tr its not working I know this css works on block level element so I have tried with wrapping the table in div and applied that css on div still table is breaking in pages Please help if you have any solution

1

There are 1 best solutions below

3
On

First of all, you need to generate your pdf for print. To do it, use this method :

await page.emulateMediaType('print');

This will allow you to control the presentation of content for print with css like break-before, see more here : https://developer.mozilla.org/en-US/docs/Web/CSS/Paged_Media

Answer

You have multiple solutions so :

  • If your table is small enough, you can put it on one page, with a css rule like style="page-break-before: always", to ensure that it start on a new page.
  • If your table is too long (most of the case for dynamics table), generate your pdf for print will repeat the table header on each page, so the pdf will still be readable. If you need to ensure that some elements groups will stay together, you can apply css rules like we saw above.

It could be an hard work to obtain precise render with puppeteer, but puppeteer is probably the best to do it for now. Be brave.