I generate html programmatically in order to have it rendered nicely for printing.
I have to print tables that may span several pages. This poses some challenges such as preventing cell contents to spread over two pages like this:
I found a solution in this answer, which uses page-break-inside:avoid
, along with this answer, which uses display: block
for the <tr>
elements in order to prevent them from getting split up vertically.
However, this also causes the rows not to vertically align with each other any more. How do I fix that?
Here's how it should look (and how the browser renders it on-screen):
And here's what it renders for printing:
How do I make the printout aligned, the samew as it's aligned on the screen, without having to lose the display: block
ability to keep cells vertically intact at page breaks? It has to work in Webkit (Safari) on macOS.
Here's the complete html code. It spans two pages so that one can check whether individual cells appear half on one and half on the next page (which is not desired):
<!DOCTYPE html><html><head><meta charset="utf-8"><style type="text/css">
th, td { border: 1px solid #aaa; }
@media print {
table, tr, td, th {
page-break-inside: avoid;
}
tr {
display: block;
page-break-before: auto;
}
}
</style></head>
<body>
<table style="width:40%">
<tr><th>A</th><th>B</th><th>C</th></tr>
<tr><td>more text<br>1<br>2<br>3<br>4<br>5<br></td><td>more text</td><td>more text</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
<tr><td>1<br>2<br>3<br>4<br>5<br>6<br></td><td>x</td><td>x</td></tr>
</table>
</body></html>
Update:
I also tried this solution which uses div
instead of table
. This gives slightly different results when printing, but still bad (now the cell heights are wrong, too):