Generate and export, batch generate and export QR codes

This type of function is generally used in management systems to generate large batches of QR codes and export compressed packages.

The following examples use vue2.x, which can be configured according to different JS language environments. 

1. Create components

// 引用组件使用方式
// import ExportQrcode from '@/components/exportQrcode/exportQrcode.vue'
// <Button style="margin-left: 8px" @click="exportQrcodes" >{
   
   {$t('export')}}</Button>
// <ExportQrcode :qrdata="list" @successExport="successExport"></ExportQrcode>
    // data(){
    //     list:[],
    //     selectData:[],
    // },
    // components: {
    //     ExportQrcode,
    // },
    // methods: {
    //     exportQrcodes(){
    //         this.list=this.selectData
    //     },
    //     successExport(){
    //         this.$refs.selection.selectAll(false)
    //         this.selectData=[]
    //         this.list=[]
    //     },
    // }
<template>
    <div>
        <div id="qrcode" class="code" ref="qrCodeDiv">
            <div v-for="(item, index) in list" :key="index" :id="'captureId'+index" class="invitationCode text-center" style="z-index:-1111;position:absolute;left:-99999;width: 600px;height: 400px;background-size: cover;">
                <div class="codeImgbox" ref="BoxImgContent" :id="'codeImgbox' + index">
                    <div style="font-size:20px;font-weight:700">{
   
   {item.companyName}}</div>
                    <div style="font-size:18px;font-weight:500;margin-bottom:20px">{
   
   {item.areaCode}}</div>
                </div>
                <div>
                    <div style="font-size:16px;font-weight:400;margin-top:10px">{
   
   {item.name}}</div>
                    <div style="font-size:16px;font-weight:400">{
   
   {item.account}}</div>
                </div>
                <br/>
            </div>
        </div>
    </div>
</template>

<script>
    import html2canvas from 'html2canvas'
    import QRCode from 'qrcodejs2'
    import JSZip from "jszip-sync"
    import FileSaver from 'file-saver';
    export default {
        name: 'export-qrcode',
        props: {
		    qrdata: { // 终端客户id,默认标记-1,用于判断外部是否有用到这个属性
                type: Array,
                default() {
                    return  []
                } 
            },
        },
        data () {
            return {
                firstFlag: true,// 用于控制dom的显隐
                canvasImageUrl: "",  // html2canvas 生成的图片链接
                list: [],
                stationCanvas: []   //保存img地址
            };
        },
        mounted () {
            // 不一定要放在这个生命周期,写成函数也行!!!
            // 因为工作需求生成100个二维码前面地址不变但是后面序号改变 所以用了这样的方式生成了一个数组,
            // 一般批量生成基本上这种循环就可以解决,当然,如果你有一个表格的数据需要生成二维码 只要数组的格式为:
            // [{url:'http:......',name:'',imgSrc:''},{url:'http:......',name:'',imgSrc:''}.....]
            //  这种格式就行,解析表格的话可以找后端协助返回给你数组也行
            // mounted生命周期以下代码是测试功能使用,开发中用美国不到可以自行删除
            // for (let index = 1; index < 5; index++) {
            //     this.list.push({
            //         url: index+'url', // 二维码的地址
            //         name: '名城'+index, // 设置每一个二维码的文件名
            //         imgSrc: '二维码',// 生成的二维码放图片的字段
            //         account: '账号'+index,
            //     })
            // }
            // // 这一步非常慢,有待优化
            // this.list.forEach((element, index) => {
            //     this.$nextTick(function () {
            //         this.qrcode(JSON.stringify(element), index)
            //     });
            // });
            // this.firstFlag = false;
            // this.$nextTick(function () {
            //     this.packageImages(); // 二维码生成后,执行生成图片,并打包
            // });
        },
        watch:{
            qrdata:function (newVal) {
                if(newVal<=0){
                    this.$Message.warning('请选择需要导出的数据')
                    return ;
                }
                this.list=newVal
                this.clickS()
            }
        },
        methods: {
            clickS(){
                // 这一步非常慢,有待优化
                this.list.forEach((element, index) => {
                    this.$nextTick(function () {
                        this.qrcode(JSON.stringify(element), index)
                    });
                });
                this.firstFlag = false;
                this.$nextTick(function () {
                    this.packageImages(); // 二维码生成后,执行生成图片,并打包
                });
            },
            // qrcode 的使用
            qrcode (data, index) {
                // data,index 是传过来的值,不用多说
                let qrcode = new QRCode(this.$refs.BoxImgContent[index], {
                    // this.$refs.qrCodeDiv.children[index].children[0] 这个是dom选择器,选择对应的dom生成二维码
                    width: 150, // 二维码的宽
                    height: 150, // 二维码的高
                    text: data, // 二维码地址--所有信息
                    colorDark: "#000",// 二维码颜色
                    colorLight: "#fff"// 二维码背景色
                    //  这里 生成的二维码可能样式达不到预期要求,文后在说一说怎么调节
                });
            },
            // 打包图片成压缩包的函数
            packageImages () {
                // 初始化stationCanvas
                this.stationCanvas = [];
                // 循环每一个类名为invitationCode的dom元素
                let doms = document.getElementsByClassName('invitationCode');
                doms = Array.from(doms);
                doms.forEach((item, index) => {
                    // 使用html2canvas 截取这个dom 并生成图片
                    html2canvas(document.querySelector("#captureId" + index)).then((canvas) => {
                        const url = canvas.toDataURL(); // 生成的图片
                        const Obj = {
                            // invitationCode这个dom的内容,可以打印(item)看一看
                            id: JSON.parse(item.children[0].getAttribute('title')).id,
                            src: url,
                        };
                        this.list.forEach((item1) => {
                            // 使用 唯一的 id值判断内容是否相等,判断是否为同一个dom元素生成的
                            if (item1.id === Obj.id) {
                                item1.imgSrc = Obj.src;//item.children[0].children[1].getAttribute('src');
                            }
                        });
                        // 然后添加到这个数组里面
                        this.stationCanvas.push(url);
                        // console.log(this.stationCanvas);
                        // 判断 this.stationCanvas 这个数组是否等于我们的原数组,也就是循环走到最后一个时,批量处理文件
                        if (this.stationCanvas.length === this.list.length) {
                            const zip = new JSZip();  // 压缩的插件方法
                            const cache = {};
                            const arr = this.list;
                            arr.forEach((item) => {
                                // 设置生成的文件名
                                const fileName = item.name+item.account;
                                // 文件名加文件流加格式
                                zip.file(`${fileName}.jpg`, item.imgSrc.substring(22), { base64: true });
                                // 这句不懂 用就完事了 ,大概就是插件需要这样的数据类型
                                cache[fileName] = item.imgSrc;
                            });
                            // 打包
                            zip.generateAsync({ type: 'blob' }).then((content) => {
                                console.log(content);
                                FileSaver.saveAs(content, '二维码.zip');//这里设置压缩包的名称
                            });
                            this.$emit('successExport',arr)
                            this.list=[]
                        }
                    }).catch(error => { });
                });
            },
        }
    }
</script>
<style lang="less">
    .codeImgbox{
        margin-top: 70px;
    }
    img{
        margin-left: 230px;
    }
    .text-center{   
        text-align: center;
    }
</style>

2. Introduce the use of components

// 引用组件使用方式
// import ExportQrcode from '@/components/exportQrcode/exportQrcode.vue'
// <Button style="margin-left: 8px" @click="exportQrcodes" >{
   
   {$t('export')}}</Button>
// <ExportQrcode :qrdata="list" @successExport="successExport"></ExportQrcode>
    // data(){
    //     list:[],
    //     selectData:[],
    // },
    // components: {
    //     ExportQrcode,
    // },
    // methods: {
    //     exportQrcodes(){
    //         this.list=this.selectData
    //     },
    //     successExport(){
    //         this.$refs.selection.selectAll(false)
    //         this.selectData=[]
    //         this.list=[]
    //     },
    // }

This is some summary I made in my work and study, and I also share it with friends who need it ~ For reference and study, if you have any suggestions, please leave a comment. Please indicate the source when reprinting, thank you for your support!

Guess you like

Origin blog.csdn.net/jiangzhihao0515/article/details/132827370