Im using html and CSS to print documents, I have to print the header and the footer on each page, which works but if the headers goes beyond a certain height, the content gets rendered on top of the header.
This is the template that i created.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./style.css" />
<style>
.page-footer {
position: fixed;
bottom: 0;
width: 100%;
}
.page-header {
position: fixed;
top: 0mm;
width: 100%;
}
@page {
margin: 15pt
}
@media print {
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
button {
display: none;
}
body {
margin: 0;
}
}
</style>
</head>
<body>
<div class="page-header" id="page-header">
<div id="header">
<!-- HEADER HTML GOES HERE-->
</div>
</div>
<div class="page-footer" id="page-footer">
<div id="footer">
<!-- FOOTER HTML GOES HERE -->
</div>
</div>
<table>
<thead>
<tr>
<td>
<!--place holder for the fixed-position header-->
<div id="page-header-space" class="page-header-space"></div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<!--*** CONTENT GOES HERE ***-->
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<!--place holder for the fixed-position footer-->
<div class="page-footer-space" id="page-footer-space"></div>
</td>
</tr>
</tfoot>
</table>
</body>
<script>
window.addEventListener("load", () => {
const header = document.getElementById("header");
const footer = document.getElementById("footer");
const headerHeight = header.scrollHeight + 20;
const footerHeight = footer.scrollHeight + 20;
document.getElementById("page-header").style.height = headerHeight + "px";
document.getElementById("page-header-space").style.height = headerHeight + "px";
document.getElementById("page-footer").style.height = footerHeight + "px";
document.getElementById("page-footer-space").style.height = footerHeight + "px";
});
</script>
</html>
I’ve tried other methods like using libraries such as selectpdf (slow), ironPdf (expensive) and others but they just don’t seem to hit the mark. So I decided to give it a try myself.
New contributor
Enver Miftari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.