If there is anyone more skilled than me who could provide an enhanced version of this code, I would greatly appreciate it. While I believe that improvements can be made with functions like breakToken
, the current setup works for my needs:
Within the unpaginated html, there exists a div labeled .back-page
. The approach taken here involves checking if the page number corresponding to the back-page div is divisible by 4. If not, a large empty div is inserted.
The JavaScript
window.PagedConfig = { auto: false };
document.addEventListener("DOMContentLoaded", function () {
class MyHandler extends Paged.Handler {
constructor(chunker, polisher, caller) {
super(chunker, polisher, caller);
}
beforeParsed(content) {}
afterParsed(parsed) {}
beforePageLayout(page) {}
afterPageLayout(pageFragment, page, breakToken) {
bumpBackPageContentToRealBackPage(pageFragment);
}
afterRendered(pages) {}
}
Paged.registerHandlers(MyHandler);
setTimeout(() => window.PagedPolyfill.preview(), 2000); // TODO: replace this with the promise version
});
function bumpBackPageContentToRealBackPage(pageFragment) {
let backPage = pageFragment.querySelector(".back-page");
if (backPage) {
let pageNumberStr = backPage.closest(".pagedjs_page").dataset.pageNumber;
let pageNumber = parseInt(pageNumberStr, 10);
console.log("last page is on", pageNumber);
if (pageNumber % 4 !== 0) {
console.log("last page needs a nudge");
let pageDiv = document.createElement("div");
pageDiv.classList.add("end-vacat-page");
backPage.parentElement.insertBefore(pageDiv, backPage);
} else {
console.log("All is well: last page will print on the back page");
}
}
}
The CSS
.back-page {
break-before: left;
}
.end-vacat-page {
page-break-before: always;
height: var(--pagedjs-pagebox-height);
}
This action triggers a reflow, ensuring that the back page aligns with the requirement to be displayed on a left-hand page according to one of the rules in the Paged.js polyfill.