I am trying to use html2pdf to download the HTML page as PDF however if the content of the table is too long, it tends to break the TR midway through.
Any solutions for this issue?
pagebreak: { avoid: ['tr', 'td'] }
var opt = {
margin: 0.5,
filename: dashboard_name + '_' + client_name + '.pdf',
pagebreak: { avoid: ['tr', 'td'] },
image: { type: 'jpeg', quality: 1 },
html2canvas: { dpi: 192, width: $(window).width()},
jsPDF: {
orientation: pageOrient,
unit: 'cm',
format: 'a2',
compress: true
}
};
@media print {
table, div {
break-inside: avoid;
}
}
thead { display: table-header-group; }
tfoot { display: table-row-group;}
tr {
page-break-after: always!important;
page-break-before: always!important;
page-break-inside: auto!important;
}
mode: ['avoid-all', 'css', 'legacy']
},`
However, the table row is still breaking across 2 pages as depicted in the image below.
Let's consider the following versions as the current versions:
html2pdf.js
: 0.10.1
.The default page-break modes: ['css', 'legacy']
.
Adding the avoid-all
page-break mode resolves the problem:
const opt = {
<…>,
pagebreak: {
mode: ['avoid-all', 'css', 'legacy']
},
<…>
};
Please, refer to the documentation section: html2pdf.js | Client-side HTML-to-PDF rendering using pure JS. | Options | Page-breaks.
index.html
) after applying solutionPlease, note and address the TODO-note appropriately.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML table</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"
integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg=="
crossorigin="anonymous"
referrerpolicy="no-referrer">
</script>
</head>
<body>
<h1>HTML table</h1>
<button onclick="printTable()">
Print to PDF
</button>
<table id="long-table">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<!-- TODO: Duplicate the below row many times. -->
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
<script defer>
function printTable() {
const element = document.getElementById('long-table');
var opt = {
pagebreak: {
mode: ['avoid-all', 'css', 'legacy']
}
};
html2pdf(element, opt);
}
</script>
</body>
</html>
An additional example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With