前言
实现效果如下图↓
一、实现思路
- 通过
qrcodejs2
插件生成二维码 - 通过
html2canvas
插件对页面指定区域进行图片生成 - 通过
print-js
插件对生成的图片进行打印
二、下载相应库
import QRCode from 'qrcodejs2';
import html2canvas from "html2canvas"; //生成图片
import printJs from "print-js"; //文件压缩
三、封装代码
- template
代码如下:
<template>
<div class="print-box">
<div ref="print" id="printBox">
<div v-for="(item, index) in QRCodeList" :key="index" class="item" ref="html2canvasRef">
<div :ref="id"></div>
<h4 v-if="item.title" class="QRCode_title">{{ item.title }}</h4>
</div>
</div>
</div>
</template>
- style
代码如下:
<style lang="less">
.print-box {
display: none;
}
</style>
- js
<script>
import QRCode from 'qrcodejs2';
import html2canvas from "html2canvas"; //生成图片
import printJS from "print-js";
export default {
data() {
return {
QRCodeList: [],
html2canvas: null,
}
},
props: {
id: {
type: String,
default: "QRCode",
required: true
},
width: {
type: String | Number,
default: 150
},
height: {
type: String | Number,
default: 150
},
colorDark: {
type: String,
default: '#000000'
},
colorLight: {
type: String,
default: '#ffffff'
},
logoUrl: {
type: String,
default: ''
},
},
methods: {
initQRCode(data = {}) {
const index = data.index;
const QRCodeRefs = this.$refs[this.id];
return new Promise((resolve) => {
const qrcode = new QRCode(QRCodeRefs[index], {
text: data.id,
width: this.width,
height: this.height,
colorDark: this.colorDark,
colorLight: this.colorLight,
correctLevel: QRCode.CorrectLevel.H,
margin: 5,
type: "image/png"
});
let canvas = qrcode._el.getElementsByTagName("canvas")[0];
if (this.logoUrl) {
let img = qrcode._el.getElementsByTagName("img")[0];
let ctx = canvas.getContext("2d");
let logo = new Image();
logo.crossOrigin = "Anonymous";
logo.src = this.logoUrl;
logo.onload = () => {
let codeWidth = (this.width * 0.8) / 2;
let codeHeight = (this.height * 0.8) / 2;
ctx.drawImage(logo, codeWidth, codeHeight, this.width * 0.2, this.height * 0.2);
img.src = canvas.toDataURL();
resolve(qrcode);
}
} else {
resolve(qrcode);
}
})
},
initQRCodeList(QRCodeList = []) {
this.QRCodeList = QRCodeList;
},
async onPrintQRCode() {
const html2canvasRefs = this.$refs.html2canvasRef;
for (let i = 0; i < this.QRCodeList.length; i++) {
const item = this.QRCodeList[i];
const QRCodeRefs = this.$refs[this.id];
QRCodeRefs[i].innerHTML = '';
await this.initQRCode({...item, index: i});
}
const style = `@media print {
#printBox {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
.item{
flex: 0 0 24%;
padding-right: calc(4% / 3);
padding-bottom: calc(4% / 3);
display: flex;
flex-direction: column;
align-items: center;
&:nth-child(4n) {
padding-right: 0;
}
&:last-child {
padding-right: auto;
}
h4{
padding: 15px 0;
text-align: center;
}
}
}
}`
setTimeout(() => {
printJS({
printable: "printBox",
type: "html",
maxWidth: "100%",
scanStyles: false,
style: style
});
})
},
},
}
</script>