vue实现二维码批量生成和打印

摘要:实现一个可以根据数据批量生成二维码标签页个批量打印标签页的组件。难点在于,文字和二维码如何合成一张图片进行打印,因为生成的二维码是图片,但文字和二维码整个内容其实是一个div。

效果展示

标签批量生成效果:

标签批量打印效果:

部分代码

<template>
  <div>
    <div id="printable-area" class="printable-area">
      <div class="title">测试</div>
      <div class="content">
        <div class="text">
          <div>字段1:{{ info.code }}</div>
          <div>字段2:{{ info.code }}</div>
          <div>字段3:{{ info.code }}</div>
        </div>
        <canvas ref="qrcodeCanvas"></canvas>
      </div>
    </div>
    <button @click="printQRCode">打印二维码</button>
  </div>
</template>

<script>

export default {
  data() {
    return {
      // 二维码内容
      qrcodeContent: '1111',
      info: {
        code: '00X1'
      }
    }
  },
  mounted() {
    this.generateQRCode()
  },
  methods: {
    generateQRCode() {
      const canvas = this.$refs.qrcodeCanvas
      QRCode.toCanvas(canvas, this.qrcodeContent, error => {
        if (error) console.error(error)
      })
    },
    
    printQRCode() {
      const canvas = this.$refs.qrcodeCanvas
      if (!canvas) {
        console.error('Canvas element not found')
        return
      }

      const printWindow = window.open('', '_blank')
      if (!printWindow) {
        console.error('Failed to open print window')
        return
      }

      printWindow.document.write('<img src="' + canvas.toDataURL('image/png') + '">')
      printWindow.document.close()
      printWindow.focus()
      printWindow.print()

      // 延迟关闭窗口,确保打印操作有足够的时间完成
      setTimeout(() => {
        printWindow.close()
      }, 2000) // 延迟2秒
    }
  }
}
</script>
<style lang="scss" scoped>
.printable-area {
  width: 220px;
  border: 1px solid;
  padding: 5px;

  .title {
    font-size: 18px;
  }

  .content {
    display: flex;

    .text {
      text-align: left;
    }
  }
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yue200403

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值