前端实现浏览器打印

本文介绍了如何在Vue应用中使用printView组件,通过将特定HTML片段传入iframe,控制浏览器仅打印所需部分,如工作订单详情。组件通过设置iframe的内容并调整页面高度来适应多页打印需求。
摘要由CSDN通过智能技术生成

浏览器的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)

}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值