网页局部打印

345 阅读1分钟

第一种:

<!--startprint1-->

<!--打印内容开始-->
<div id=wdf>
    ...
</div>
<!--打印内容结束-->

<!--endprint1-->
<input type='button' name='button_export' title='打印1' onclick=preview(1) value='打印1'>
<script language="javascript">
function preview(fang)
{
if (fang < 10){
bdhtml=window.document.body.innerHTML;//获取当前页的html代码
sprnstr="<!--startprint"+fang+"-->";//设置打印开始区域
eprnstr="<!--endprint"+fang+"-->";//设置打印结束区域
prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+18); //从开始代码向后取html
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
window.document.body.innerHTML=prnhtml;
window.print();
window.document.body.innerHTML=bdhtml;
} else {
window.print();
}
}
</script>

第二种:

function preview() {
    const printHtml = document.querySelector('.print-content')
        .innerHTML // 需要打印的内容
    window.document.body.innerHTML = printHtml
    window.print()
    window.location.reload() // 打印完成后重新加载页面
}

第三种:

<style>
@media print {
    // 不打印
    .noprint { display: none; }
    // 打印背景颜色
    .bg-color {
        -webkit-print-color-adjust: exact;
    }
}
</style>
//页面打印缩放比例设置
document.getElementsByTagName('body')[0].style.zoom=0.92;
<!--不显示页眉页脚-->
<style media="print">
    @page {
        size: auto;  /* auto is the initial value */
        margin: 0mm; /* this affects the margin in the printer settings */
    }
</style>