如何使用vue-print-nb ,根据后端返回的图片blob流在线调取打印机,打印图片,打印指定区域

搜遍全网感觉没有一个做过的,只能看类似的案例,自己摸索了,索性很容易就出来了,记录一下

首先,我们需要打印后端返回的图片流,我找了半天没找到方法,打印pdf的方法倒是有,但只是支持pdf的流。

那么打印图片流,只能考虑其他的方案了。变通思路如下:

blob的图片流肯定能展示在页面上,那么只要先把图片转成blobURL的地址,显示在指定的div内,然后指定打印的区域就行了。

做法如下: 

1.先把返回的blob流,转成blob的URL:

 // 将返回的流数据转换为url, flle参数是blob流
    getObjectURL(file) {
      let url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file);
        } catch (error) {}
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file);
        } catch (error) {}
      }
      return url;
    }

2.然后把这个地址,放在指定div的里面,我这里写了个子组件:

打印图片组件
<template>
  <div class="printImage">
    <img :src="imageUrl" id="printme" />
    <button v-show="false" v-print="'#printme'" id="print">打印</button>
  </div>
</template>

<script>
import print from 'vue-print-nb'
export default {
  directives: {
    print   
  },
  props:['imageUrl'],
  methods: {
    startPrint(){
      // 开始打印
      document.getElementById('print').click()
    }
   }
}
</script>

<style lang="scss" scoped>
/* 这里的样式控制 打印区域不显示在网页可视区域内,可以让用户无感打印*/
.printImage{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  z-index: -99999999999;
}
#printme{
  width: 990px;
  margin: 0 auto;
}
@media print{
  html,body{
    height: inherit;
  }
}
</style>

3. 父组件使用:

引入子组件

···
components: {
    printImage: () => import('./printImage')
  },
····

页面使用:

<printImage ref="pma" :imageUrl="imageUrl" />

然后在点击确认打印,获取接口返回流的部分,添加如下代码:

 this.imageUrl = this.getObjectURL(res.data)
 this.$refs.pma.startPrint()

如果你在打印的时候,发现显示不全,请找我,我来告诉你,为啥。。。

记录一下,全网都没我这个需求,我真的是服了。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值