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