1.前言
这两天项目中遇到一个打印的功能,对表格数据打印,并且表格的footer底部内容是用户手动输入的。由于是第一次做打印功能我上网搜了一些方案比如:1.直接通过window.print()打印如图
这种方式存在弊端就是他会替换dom元素打印但是对应通过类名引入样式是无法生效的,就是只能把样式写到style里面,如果样式很多就不方便。 2.创建一个Iframe标签然后把打印元素放进去也可以实现打印,但是同上面的一样通过类名引入的样式不生效。
html
<div id="printId">
打印内容
<h1 class="h1color">颜色变化</h1>
</div>
<script>
let bth = document.querySelector('button')
bth.addEventListener('click', onIframePrint)
function onIframePrint() {
const printContentHtml = document.getElementById("printId").innerHTML;
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
iframe.contentDocument.write(printContentHtml);
iframe.contentDocument.close();
iframe.contentWindow.print();
document.body.removeChild(iframe);
}

2.我的解决方案
这种方式就是对HTML和CSS进行拼接,这样引入的CSS就可以生效。并且的打印的文本可以让用户手动输入一部分最后将值打印出来,相比之前的解决方案更加灵活。
js
function innerHtmlPrint() {
// 创建打印专属样式
const printStyles = `
<style>
body {
background: white;
font-family: Arial, sans-serif;
margin: 0;
padding: 10mm;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.print-header {
margin-bottom: 10mm;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
font-size: 9px;
}
</style> `;
// 获取打印内容
const printContent = document.querySelector('.printcontent')?.innerHTML;
// 创建打印文档
const printDocument = `
<!DOCTYPE html>
<html>
<head>
${printStyles}
</head>
<body>
<h4 style={{ fontWeight: 500 }}>${parentData.batchName}</h4>
${printContent}
<div class="printFooter">
<span>技术员:${printData.technician}</span>
<span>配矿人:${printData.miner}</span>
<span>生成技术部:${printData.techDept}</span>
<span>焙烧制酸厂:${printData.acidPlant}</span>
</div>
<script>
window.onload = function() {
window.print();
setTimeout(function() {
window.close();
}, 100);
}
</script>
</body>
</html>
`;
// 打开打印窗口
const printWindow = window.open('', '_blank');
if (printWindow) {
printWindow.document.write(printDocument);
printWindow.document.close();
}
}
3.打印样式优化手段
对打印来说最头疼的就是对样式的优化,有时候在页面写好的样式在打印的时候就会有些问题。
1.@print
通过CSS每天查询@print修改样式
css
<style>
@media print {
body {
background: white;
font-family: Arial, sans-serif;
margin: 0;
padding: 10mm;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
/* 其他打印专属样式 */
}
</style>
2.@Page
@page
at 规则是一种 CSS 规则,用于修改打印页面的不同方面。它的目标是修改页面的尺寸、方向和页边距。@page
at 规则可用于针对打印输出中的所有页面,也可使用其各种伪类来针对一个子集。

其他
在询问AI的过程中提到了这样一个样式,可以解决表格跨页显示的问题,这个我没有试过不知道行不行。
