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'
|
import expressions from 'angular-expressions'
|
import PizZipUtils from 'pizzip/utils/index.js'
|
/**
|
* 将base64格式的数据转为ArrayBuffer
|
* @param {Object} dataURL base64格式的数据
|
*/
|
function base64DataURLToArrayBuffer(dataURL) {
|
const base64Regex = /^data:image\/(png|jpg|jpeg|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 = Buffer.from(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;
|
}
|
export default {
|
chartToImageUrl(chart) {
|
const dataURL = chart.getDataURL({
|
pixelRatio: 5, // 提高图片质量
|
backgroundColor: '#FFFFFF', // 设置背景颜色
|
excludeComponents: ['toolbox'], // 排除工具箱组件
|
type: 'png' // 输出图片类型为PNG
|
});
|
return dataURL;
|
},
|
/**
|
* 导出word文档(带图片)
|
*
|
*/
|
|
|
ExportBriefDataDocx(tempDocxPath, data, fileName, imgSize) {
|
expressions.filters.lower = function(input) {
|
if (!input) return input
|
return input.toLowerCase()
|
}
|
|
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
|
if (error) {
|
console.log(error)
|
}
|
expressions.filters.size = function(input, width, height) {
|
return {
|
data: input,
|
size: [width, height]
|
}
|
}
|
let opts = {}
|
opts = {
|
// 图像是否居中
|
centered: false
|
}
|
opts.getImage = (chartId) => {
|
//将base64的数据转为ArrayBuffer
|
return base64DataURLToArrayBuffer(chartId);
|
}
|
opts.getSize = function(img, tagValue, tagName) {
|
console.log("img, tagValue, tagName", img, tagValue, tagName);
|
|
if (imgSize[tagName]) {
|
console.log("imgSize[tagName]", imgSize[tagName]);
|
return imgSize[tagName]
|
} else {
|
return [300, 300]
|
}
|
}
|
// 创建一个JSZip实例,内容为模板的内容
|
|
const zip = new PizZip(content)
|
// 创建并加载 Docxtemplater 实例对象
|
// 设置模板变量的值
|
const doc = new Docxtemplater()
|
doc.attachModule(new ImageModule(opts))
|
doc.loadZip(zip)
|
doc.setOptions({
|
nullGetter: function() { // 设置空值 undefined 为''
|
return ''
|
}
|
})
|
doc.setData(data)
|
try {
|
// 呈现文档,会将内部所有变量替换成值,
|
doc.render()
|
} catch (error) {
|
const e = {
|
message: error.message,
|
name: error.name,
|
stack: error.stack,
|
properties: error.properties
|
}
|
console.log('err', { error: e })
|
// 当使用json记录时,此处抛出错误信息
|
throw error
|
}
|
// 生成一个代表Docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
|
const out = doc.getZip().generate({
|
type: 'blob',
|
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
})
|
// 将目标文件对象保存为目标类型的文件,并命名
|
saveAs(out, fileName)
|
})
|
}
|
}
|