I’m working on this task for 3 days now. I feel like I need to ask someone who’s well verse in JavaScript. I read multiple documentation about window.print() but I still do not get any fix.
Here’s my problem.
This is my html which is dynamically generated:
<body>
<div class="page-break page" data-div="0" id="printDiv_0">...long content here...</div>
<div class="page-break page" data-div="1" id="printDiv_1">...long content here..</div>
</body>
Now, when printing, I have a working code JS code except, when a div has multiple pages, it only add the prependedHeader to the 1st page, the subsequent pages is empty:
const testx = () => {
const docs = document.querySelectorAll('.page-break');
const createHeader = (leftText, rightText) => {
const header = document.createElement('div');
header.style.display = 'flex';
header.style.justifyContent = 'space-between';
header.style.paddingRight = '10px';
header.style.paddingLeft = '10px';
header.style.alignItems = 'center';
header.style.marginBottom = '0px';
header.style.fontWeight = 'bold';
header.style.fontSize = '15px';
header.classList.add("font-weight-bold");
header.classList.add("print-header-div");
// Left column
const leftDiv = document.createElement('div');
leftDiv.textContent = leftText;
// Right column
const rightDiv = document.createElement('div');
rightDiv.textContent = rightText;
header.appendChild(leftDiv);
header.appendChild(rightDiv);
return header;
};
docs.forEach((div, index) => {
// Safely retrieve elements and fallback to defaults if missing
const sectionId = div.getAttribute('data-div') || `Section ${index + 1}`;
const requestCode = div.querySelector('#RequestCode')?.value || 'Unknown Request Code';
const lastName = div.querySelector('.print-last-name')?.innerHTML || 'Unknown Last Name';
const firstName = div.querySelector('.print-first-name')?.innerHTML || 'Unknown First Name';
const dob = div.querySelector('.print-dob')?.innerHTML || 'Unknown DOB';
// Generate the eOrderIdentity
const eOrderIdentity = `${requestCode} ${lastName} ${firstName} ${dob}`;
// Get total pages for the current div (assuming it has content that spans multiple pages)
const totalPages = calculatePageCount(div)
const currentPage = 1; // For single div context, always start at 1
// Create and prepend a header for the current page
const prependedHeader = createHeader(
`${eOrderIdentity}`,
`Page ${currentPage} of ${totalPages}`
);
div.insertBefore(prependedHeader, div.firstChild);
});
// Trigger the print dialog
window.print();
};
// Letter size by default
function calculatePageCount(content, pageHeight = 1056, pageWidth = 216) {
let contentElement;
if (typeof content === 'string') {
contentElement = document.createElement('div');
contentElement.innerHTML = content;
} else if (content instanceof HTMLElement) {
contentElement = content.cloneNode(true);
} else {
throw new Error('Invalid content. It must be an HTML string or a DOM element.');
}
contentElement.style.cssText = `
visibility: hidden;
position: absolute;
width: ${pageWidth}mm;
top: -9999px;
`;
document.body.appendChild(contentElement);
const contentHeight = contentElement.scrollHeight;
const totalPages = Math.ceil(contentHeight / pageHeight);
//document.body.removeChild(contentElement);
return totalPages;
}
Each div prependedHeader
will reset on the next div.
For example:
The 1st div has 3 pages, the Header on each page will be Page 1 of 3, Page 2 of 3, Page 3 of 3.
The 2nd div has 2 pages, the Header on each page will be Page 1 of 2, Page 2 of 2.
Same for 1 paged div.
they will all be printed when the window.print() is called.
Thanks in advance!