浏览器的print方法直接调用会打印当前页面的所有元素,使用iframe可以实现局部打印所需要的模块。
组件printView,将传入的信息放入iframe中,调用浏览器的打印功能
<template><div class="print"><iframeid="iframe"style="display: none; width: 100%"frameborder="0"></iframe></div>
</template>
<script>
export default {name: 'printView',methods: {setBodyHtml(html) {const document = window.documentconst iframe = window.frames[0]iframe.document.head.innerHTML = document.head.innerHTML // 获取当前文档的头部给iframeiframe.document.body.innerHTML = html // 把传过来的html给iframe头部iframe.document.body.style.background = '#fff'let arr = document.getElementsByTagName('tr')let heightNum = 0let onePage = 800 //第一页的高度for (let i in arr) {heightNum += arr[i].offsetHeightif (heightNum > onePage) {heightNum = arr[i].offsetHeightonePage = 1500 //第二页高度}}iframe.window.print()}}
}
</script>
<div v-if="detail.work_order_id" class="before" id="print_info">
<work-order-detail :detail="detail"></work-order-detail>
</div>
// 打印
const viewRef = ref(null)
const print = () => {
const html = document.getElementById('print_info').innerHTML
viewRef.value.setBodyHtml(html)
}