Print format add auto page number

This should work for A4 sized pages

<script>
window.onload = function() {

    const pageHeightPx = 1122.510;
    const headerHeight = document.querySelector('.print-head').getBoundingClientRect().height;
    const footerHeight = document.querySelector('.print-foot').getBoundingClientRect().height;
    const actualPageHeightPx = pageHeightPx - headerHeight - footerHeight - 169;
    const bodyElement = document.querySelector('.print-body');
    const currentBodyHeight = bodyElement.getBoundingClientRect().height;
    const numberOfPages = Math.ceil(currentBodyHeight / actualPageHeightPx);
    const printFormatDiv = document.querySelector('.print-format');
    const contentDiv = document.getElementById('print-content');

    for (let i = 0; i < numberOfPages; i++) {
        const pageNumberDiv = document.createElement('div');
        pageNumberDiv.classList.add('page-number');
        pageNumberDiv.textContent = `Page ${i + 1} of ${numberOfPages}`;
        pageNumberDiv.style.top = `${(i * pageHeightPx) + 4}px`;
        printFormatDiv.appendChild(pageNumberDiv);
    }
}
</script>

Things that might cause faulty page numbering;

  • Adding a page break.
  • Displaying theads as table header group (you will need to account for theads’ heights that repeat on every page). To solve this;
if (numberOfPages > 1) {
        const theads = document.querySelectorAll('.print-format table thead');
        let totalTheadHeight = 0;
        theads.forEach(thead => {
            totalTheadHeight += thead.getBoundingClientRect().height;
        });

        const actualBodyHeight = currentBodyHeight + totalTheadHeight * (numberOfPages - 1);
        const tempNumberOfPages = Math.ceil(actualBodyHeight / actualPageHeightPx);

        const newBodyHeight = currentBodyHeight + totalTheadHeight * (tempNumberOfPages - 1);
        const newNumberOfPages = Math.ceil(newBodyHeight / actualPageHeightPx);
}

Then you can use the newNumberOfPages in your for loop.