I tried first the sweet solution provided by @MauriceNino but noticed some throwback such as not preserving styles and fonts.
Therefore I opened an issue (that has been closed in favor of this issue) in the Ionic repo and developed the following workaround.
Basically, instead of copying the content in a popup, I clone the targeted node that contains the content at the body
root and remove it after print or when the use click the "cancel" button in the print modal.
export const print = ({element}: {element: Node}) => {
const body: HTMLBodyElement | null = document.querySelector('body');
if (!body) {
return;
}
const appRoot: HTMLElement | null = body.querySelector('app-root');
let node: Node | null | undefined = undefined;
window.addEventListener(
'afterprint',
() => {
if (node) {
body.removeChild(node);
}
appRoot?.classList.remove('hidden');
},
{once: true}
);
const onRender = async (_mutations: MutationRecord[], observer: MutationObserver) => {
observer.disconnect();
// Here you can do other things you need such as lazy loading content if you need too
appRoot?.classList.add('hidden');
window.print();
};
const docObserver: MutationObserver = new MutationObserver(onRender);
docObserver.observe(body, {childList: true, subtree: true});
node = body?.appendChild(element.cloneNode(true));
};
In addition, while printing, I hide the Ionic nodes. To do so I also defined following css (I am in a Stencil app that's why I target app-root
):
@media print {
app-root.hidden {
display: none;
}
}
Note the most beautiful hack but, does the job. Hopefully the issue will be solved soon.