this solution worked for me to add page numbers to my HTML once the user clicks ctrl + P.
how can I have the script remove the page numbers once the users finished the print job? (not sure how to remove a function with javascript)
I used this solution to implement the JavaScript code: https://stackoverflow.com/a/64884005
JavaScript
x
15
15
1
window.onload = addPageNumbers;
2
3
function addPageNumbers() {
4
var totalPages = Math.ceil(document.body.scrollHeight / 1123); //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi,
5
for (var i = 1; i <= totalPages; i++) {
6
var pageNumberDiv = document.createElement("div");
7
var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
8
pageNumberDiv.style.position = "absolute";
9
pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
10
pageNumberDiv.style.height = "16px";
11
pageNumberDiv.appendChild(pageNumber);
12
document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
13
pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
14
}
15
}
JavaScript
1
19
19
1
<html>
2
<head>
3
<style type="text/css">
4
@page {
5
size: A4;
6
margin: 0;
7
}
8
9
body {
10
margin: 0;
11
}
12
</style>
13
</head>
14
<body>
15
<div id="content">
16
Lorem ipsum .
17
</div>
18
</body>
19
</html>
JavaScript
1
4
1
Lorem ipsum .
2
</div>
3
</body>
4
Advertisement
Answer
Hi and welcome to stack overflow.
In a nutshell, give each div you add a unique class. After you have printed the pages, run a script to select all the divs with that class and delete them.
after your line of code
JavaScript
1
2
1
pageNumberDiv.style.height = "16px";
2
add this
JavaScript
1
2
1
pageNumberDiv.classList.add("page-num");
2
Then add a function
JavaScript
1
7
1
function removePageNumbers(className) {
2
let elements = document.getElementsByClassName(className);
3
while(elements.length > 0){
4
elements[0].parentNode.removeChild(elements[0]);
5
}
6
}
7
and call it
JavaScript
1
2
1
removePageNumbers("page-num")
2