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