js怎么实现表格打印
使用window.print()方法打印整个页面
在HTML中创建一个表格,并通过JavaScript调用window.print()方法触发浏览器打印功能。这种方式会打印整个页面内容,包括表格。
<table id="printTable">
<tr><th>姓名</th><th>年龄</th></tr>
<tr><td>张三</td><td>25</td></tr>
<tr><td>李四</td><td>30</td></tr>
</table>
<button onclick="window.print()">打印表格</button>
创建打印专用样式表
通过CSS媒体查询设置打印时的样式,隐藏不需要打印的元素,优化表格打印效果。

<style>
@media print {
body * {
visibility: hidden;
}
#printTable, #printTable * {
visibility: visible;
}
#printTable {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用iframe实现局部打印
创建一个隐藏的iframe,将表格内容复制到iframe中,然后打印iframe内容。

function printTable() {
const table = document.getElementById('printTable');
const printWindow = document.createElement('iframe');
printWindow.style.display = 'none';
document.body.appendChild(printWindow);
printWindow.contentDocument.write('<html><head><title>打印表格</title></head><body>');
printWindow.contentDocument.write(table.outerHTML);
printWindow.contentDocument.write('</body></html>');
printWindow.contentDocument.close();
printWindow.contentWindow.focus();
printWindow.contentWindow.print();
document.body.removeChild(printWindow);
}
使用CSS控制分页打印
通过CSS的page-break属性控制表格打印时的分页行为,避免表格被截断。
@media print {
table {
page-break-inside: avoid;
}
tr {
page-break-inside: avoid;
page-break-after: auto;
}
}
使用第三方库实现高级打印功能
可以使用jsPDF等第三方库将表格导出为PDF后再打印,实现更复杂的打印需求。
function printWithJsPDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const table = document.getElementById('printTable');
doc.autoTable({
html: table,
theme: 'grid',
headStyles: { fillColor: [22, 160, 133] }
});
doc.save('table.pdf');
// 或者直接打印
// doc.autoPrint();
// window.open(doc.output('bloburl'));
}






