vue +echarts+ docxtemplater导出word和多张图表图片

2023-10-14 07:59

本文主要是介绍vue +echarts+ docxtemplater导出word和多张图表图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

vue +echarts+ docxtemplater导出word和多张图表图片

  • 前期准备

前期准备

1、按照依赖的插件docxtemplater、pizzip、jszip-utils、jszip、FileSaver、docxtemplater-image-module-free。

//-- 安装 docxtemplater
npm install docxtemplater pizzip  --save
//-- 安装 jszip-utils
npm install jszip-utils --save 
//-- 安装 jszip
npm install jszip --save
//-- 安装 FileSaver
npm install file-saver --save
//安装 docxtemplater-image-module-free
npm install --save docxtemplater-image-module-free 

2、引入依赖

import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
import ImageModule from 'docxtemplater-image-module-free '

注:若引入docxtemplater-image-module-free 报错时,可尝试使用require方法引入。

let ImageModule = require('docxtemplater-image-module-free');

3、代码-父组件
我是把table通过插槽的方式注入到子组件的

<template><div class="box">
<wordexportFileName="测试666"templateFileName="templateFile":wordData="wordData":chartOptions="chartOptions"><template v-slot:table><table cellspacing="0"><caption>标题</caption><tr><td class="key-name">标题1</td><td colspan="3">{{ wordData.a }}</td></tr><tr><td class="key-name">标题2</td><td colspan="3">{{ wordData.b }}</td></tr><tr><td class="key-name">标题3</td><td colspan="3">{{ wordData.c }}</td></tr><tr><td class="key-name">标题4</td><td>{{ wordData.d }}</td><td class="key-name">标题6</td><td>{{ wordData.f }}</td></tr><tr><td class="key-name">标题5</td><td>{{ wordData.e }}</td><td class="key-name">标题7</td><td>{{ wordData.g }}</td></tr><tr><td colspan="4" class="key-name options">审批意见</td></tr><tr><td colspan="4" class="options">{{ wordData.h }}</td></tr><tr v-for="(item, index) in wordData.list" :key="index"><td class="key-name">姓名</td><td>{{ item.name }}</td><td class="key-name">电话</td><td>{{ item.phone }}</td></tr></table></template></word>
</div>
</template>
<script>
// 子组件
import word from "@/components/exportWord.vue";
export default {components: { word },data() {return {// 导出wordwordData: {a: "这是标题1内容",b: "这是标题2内容",c: "这是标题3内容",d: "这是标题4内容",e: "这是标题5内容",f: "这是标题6内容",g: "这是标题7内容",h: "同意",list: [{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },{ name: "王五", phone: "18888888888" },],},// 图表chartOptions: [// echarts图表的option// 第一个图表{title: {text: "某站点用户访问来源",subtext: "纯属虚构",left: "center",},tooltip: {trigger: "item",},legend: {orient: "vertical",left: "left",},series: [{name: "访问来源",type: "pie",radius: "50%",data: [{ value: 1048, name: "搜索引擎" },{ value: 735, name: "直接访问" },{ value: 580, name: "邮件营销" },{ value: 484, name: "联盟广告" },{ value: 300, name: "视频广告" },],emphasis: {itemStyle: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: "rgba(0, 0, 0, 0.5)",},},},],},// 第二个图表{title: {text: "未来一周气温变化",subtext: "纯属虚构",},tooltip: {trigger: "axis",},legend: {data: ["最高气温", "最低气温"],},xAxis: {type: "category",boundaryGap: false,data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],},yAxis: {type: "value",axisLabel: {formatter: "{value} °C",},},series: [{name: "最高气温",type: "line",data: [10, 11, 13, 11, 12, 12, 9],markPoint: {data: [{ type: "max", name: "最大值" },{ type: "min", name: "最小值" },],},markLine: {data: [{ type: "average", name: "平均值" }],},},{name: "最低气温",type: "line",data: [1, -2, 2, 5, 3, 2, 0],markPoint: {data: [{ name: "周最低", value: -2, xAxis: 1, yAxis: -1.5 }],},markLine: {data: [{ type: "average", name: "平均值" },[{symbol: "none",x: "90%",yAxis: "max",},{symbol: "circle",label: {position: "start",formatter: "最大值",},type: "max",name: "最高点",},],],},},],},],};},};
</script>

4、代码-子组件

<template><!-- 导出word模版 --><div class="approvalNo-or-opinionNo-list"><el-button type="primary" size="small" @click="exportWord">点击下载</el-button><div id="pdfDom"><slot name="table"></slot></div><divstyle="width: 600px; height: 300px; margin: 0 auto"v-for="(item, index) in chartOptions":key="index"><Echart :options="item" ref="chart"></Echart></div></div>
</template><script>
import docxtemplater from "docxtemplater";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import JSZip from "jszip";
import PizZip from "pizzip";
import Echart from "@/components/Echarts.vue";
export default {components: { Echart },data() {return {};},props: {// 文档数据wordData: {type: Object,default: {},},// 导出文件名字exportFileName: {type: String,default: "word",},// 模版文件名字(文件需放在public目录下,文件格式为docx)templateFileName: {type: String,default: "templateFile",},// 图表option 数组,可多个图表chartOptions: {type: Array,default: [],},},methods: {// 导出echarts图片,格式转换base64DataURLToArrayBuffer(dataURL) {const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;if (!base64Regex.test(dataURL)) {return false;}const stringBase64 = dataURL.replace(base64Regex, "");let binaryString;if (typeof window !== "undefined") {binaryString = window.atob(stringBase64);} else {binaryString = new Buffer(stringBase64, "base64").toString("binary");}const len = binaryString.length;const bytes = new Uint8Array(len);for (let i = 0; i < len; i++) {const ascii = binaryString.charCodeAt(i);bytes[i] = ascii;}return bytes.buffer;},// 导出文档exportWord() {const ImageModule = require("docxtemplater-image-module-free");const that = this;// 存放echarts 图表 base64图片数组const str = [];// 读取并获得模板文件的二进制内容JSZipUtils.getBinaryContent(`${that.templateFileName}.docx`,(error, content) => {if (error) {// 抛出异常throw error;}const zip = new PizZip(content); // 创建一个JSZip实例,内容为模板的内容const doc = new docxtemplater();doc.loadZip(zip); // 创建并加载docxtemplater实例对象//   如果有echarts图表if (that.chartOptions.length > 0) {for (const iterator of that.$refs["chart"]) {// 这个getChartImg方法是我的echart组件中获取echarts图表图片的base64的dataurliterator.getChartImg((chartImg) => {str.push({ image: chartImg });});}// 图片处理const opts = {};opts.centered = true; // 图片居中,在word模板中定义方式为{%%image}opts.fileType = "docx";opts.getImage = (chartId) => {return that.base64DataURLToArrayBuffer(chartId);};opts.getSize = () => {return [600, 300];};const imageModule = new ImageModule(opts);doc.attachModule(imageModule);}doc.setData({ ...that.wordData, chartlist: str }); // 设置模板变量的值try {doc.render(); // 用模板变量的值替换所有模板变量} catch (error) {const e = {message: error.message,name: error.name,stack: error.stack,properties: error.properties,};console.log(JSON.stringify({ error: e }));throw error; // 抛出异常}// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)const out = doc.getZip().generate({type: "blob",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",});// 将目标文件对象保存为目标类型的文件,并命名saveAs(out, `${that.exportFileName}.docx`);});},},
};
</script><style lang="less">
.approvalNo-or-opinionNo-list {height: 350px;overflow-y: auto;padding-bottom: 20px;border-bottom: 1px solid #ccc;> #pdfDom {table {text-align: center;border-bottom: 1px solid #ccc;width: 93%;margin: 0 auto;font-family: "楷体", "楷体_GB2312";caption {font-size: 16px;text-align: center;line-height: 46px;color: #333;font-weight: bold;}td {width: 25%;height: 32px;color: #666;border-left: 1px solid #ccc;border-top: 1px solid #ccc;padding: 0 6px;}td:last-child {border-right: 1px solid #ccc;}.key-name {color: #333;font-weight: 600;}.options {padding: 10px;text-align: justify;text-indent: 2em;}}}
}
</style>

5、getChartImg方法

// 获取图表base64图getChartImg(callback: any) {const that = this as any;callback(that.myChart.getDataURL());},

5、word模版
在这里插入图片描述
6、页面
在这里插入图片描述

7、成功导出后的word
在这里插入图片描述

这篇关于vue +echarts+ docxtemplater导出word和多张图表图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/209174

相关文章

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

关于MongoDB图片URL存储异常问题以及解决

《关于MongoDB图片URL存储异常问题以及解决》:本文主要介绍关于MongoDB图片URL存储异常问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录MongoDB图片URL存储异常问题项目场景问题描述原因分析解决方案预防措施js总结MongoDB图

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例