不应用@Media打印样式



Stackblitz:https://stackblitz.com/edit/angular-xvdy1q
我想打印特定的div

<div id="forPrint" (click)="onPrint('23')">
<div id="printable">
<div class="box">
</div>
</div>
</div>

Javascript 代码:

onPrint(url) {
this.mode = 'print';
const 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(`<h1> www.${url}</h1>`);
mywindow.document.write(document.getElementById('forPrint').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}

斯特莱尔斯:

@media print {
html,
body {
height: 100% !important;
width: 100%!important;
h1 {
color: #1c7430;
}
}
#printable {
display: flex!important;
justify-content: center!important;
align-items: center!important;
height: 100% !important;
width: 700px!important;
}
.box {
width: 100px!important;
height: 100px!important;
background: green!important;
}
}

但是打开打印对话框后,该框不显示。因此,不会应用任何样式,例如h1.box。问题出在哪里?提前谢谢。

您需要以某种方式将CSS注入新页面。

在这里,我创建一个style标签并直接添加 CSS。您也可以链接到样式表:

function onPrint(url) {
this.mode = 'print';
const mywindow = window.open('', 'PRINT', 'height=400,width=600');
const styles = `html,
body {
height: 100% !important;
width: 100%!important;
}
h1 {
color: #1c7430;
}
#printable {
display: flex!important;
justify-content: center!important;
align-items: center!important;
height: 100% !important;
width: 700px!important;
}
.box {
width: 100px!important;
height: 100px!important;
background: green!important;
}`
mywindow.document.write(`<html><head><title>${document.title}</title>`);
mywindow.document.write(`<style>${styles}</style>`)
mywindow.document.write('</head><body >');
mywindow.document.write(`<h1> www.${url}</h1>`);
mywindow.document.write(document.getElementById('forPrint').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}

JSFiddle Demo

打印时需要启用背景颜色和图像。您可以在Chrome中"高级设置"下的打印对话框中执行此操作。

还可以应用-webkit-print-color-adjust: exact;属性来更改背景打印行为。

最新更新