前端代码

基于Vue的v-charts图表导出并下载

2019-01-29  本文已影响39人  areil2me

基于v-charts的图表功能实现的单个图表下载功能。

HTML

<div ref="box"></div>

JS

methods : {
    doPrint () {
        this.createImage();
        this.$nextTick(() => {
            if (this.$refs.box.innerHTML) {
                let PrintContent = document.getElementById('print-content');
                let newContent = PrintContent.innerHTML;
                let oldContent = document.body.innerHTML;
                document.body.innerHTML = newContent;
                window.print();
                window.location.reload();
                document.body.innerHTML = oldContent;
                return false;
            }

        });
    },
    createImage () {
        const canvas = document.getElementsByTagName('canvas')[0];
        let image = canvas.toDataURL({
            type: "png",
            pixelRatio: 2,
            backgroundColor: '#fff',//不设置此项,导出图片的底色是黑色
        });
        //在页面中展示
        box.innerHTML = '<img src="' + image + '" alt="">';
        //下载
        this.downloadFile('测试.png', image);
    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);

        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
    },
    //base64转blob
    base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
    }
}
上一篇下一篇

猜你喜欢

热点阅读