我正在处理一个离子5应用程序,它是作为一个网络应用程序构建的。它没有移动组件。
我需要允许用户打印页面。当我有一个打印按钮并与下面的函数相关联时,它只打印可视区域。
printPage() {
window.print();
}
考虑到屏幕上的内容数量,我可以看出这个文档应该有2-3页长。
我看到有一个cordova-plugin-printer
插件,但它是用来从移动设备打印的。
打印整个DOM的正确方法是什么?
发布于 2020-08-03 09:38:44
最近,我遇到了类似的情况,最后在我的项目中创建了一个角组件,这是受电子ngx-打印启发的。
唯一的限制是,对于要打印的部分,必须将*.css
文件传递给此组件。
我已经为您创建了一个stackblitz,看看它是否对您有用。
发布于 2020-08-03 12:07:39
这可能发生,因为一个可滚动的div,或者类似的东西,嵌套在主体中。
为了解决这个问题,您可以从另一个StackOverflow问题中手动选择要打印的内容,方法如下:
printPage() {
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body>');
mywindow.document.write(document.getElementById('#printArea').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
}
发布于 2021-11-05 17:41:07
我首先尝试了@MauriceNino提供的甜解决方案,但注意到了一些回滚,比如不保留样式和字体。
因此,我在Ionic中打开了一个问题 (已经关闭以支持本期),并开发了以下解决方法。
基本上,我没有在弹出窗口中复制内容,而是克隆在body
根目录下包含内容的目标节点,并在打印后或在使用时单击打印模式中的"cancel“按钮将其删除。
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));
};
此外,在打印时,我隐藏了离子节点。为此,我还定义了以下css (我在一个模板应用程序中,这就是为什么我以app-root
为目标):
@media print {
app-root.hidden {
display: none;
}
}
注意最漂亮的黑客,但是,做的工作。希望这个问题很快就能解决。
https://stackoverflow.com/questions/63178845
复制相似问题