Any way to do page breaks with javascript (print media)?

823 Views Asked by At

Browser support for page-break-inside: avoid is poor. There are lots of scenarios where it's not applied. In my case it's a nested flexbox with flex-wrap.

Is there any way to add a page break using javascript?

I can detect if the browser is in print mode with onbeforeprint event in FF, or window.watchMedia on Chrome, but what next?

I guess I need to find out what's the printed page size in pixels, so I can determine the position where to insert the page break. But window.screen.availHeight returns the same value and window.print.availHeight does not exist :(

Assuming this is possible somehow, how do I do the page break then?

1

There are 1 best solutions below

0
On

You can try a calculation, A4 has a certain proportion between width and height, so simply said if your print css makes the html/body 900px width. The height for each print page can be calculated by using the A4 proportions.

So you can add a print css file that changes the layout so that the content that needs to be on the next page has a margin top.