Skip to content
Advertisement

Remove page numbers on pages once user completes there printing html + Javascript

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

          window.onload = addPageNumbers;

          function addPageNumbers() {
            var totalPages = Math.ceil(document.body.scrollHeight / 1123);  //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi, 
            for (var i = 1; i <= totalPages; i++) {
              var pageNumberDiv = document.createElement("div");
              var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
              pageNumberDiv.style.position = "absolute";
              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)
              pageNumberDiv.style.height = "16px";
              pageNumberDiv.appendChild(pageNumber);
              document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
              pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
            }
          }
<html>
    <head>
        <style type="text/css">
            @page {
              size: A4;
              margin: 0; 
            }

            body {
              margin: 0;
            }
        </style>
    </head>
    <body>
    <div id="content">
            Lorem ipsum....
        </div>
    </body>
</html>
        Lorem ipsum....
    </div>
</body>

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

pageNumberDiv.style.height = "16px";

add this

pageNumberDiv.classList.add("page-num");

Then add a function

function removePageNumbers(className) {
    let elements = document.getElementsByClassName(className);
    while(elements.length > 0){
       elements[0].parentNode.removeChild(elements[0]);
    }
}

and call it

removePageNumbers("page-num")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement