简单说一下什么是docxtemplater,这玩意就是一个将页面展示的内容写入到word的插件。 挺好用的但是坑也比较多。怎么使用和具体详情API我这里就不阐述了,大家搜一搜都有。写这篇是也是因为自己在使用过程中遇到很多坑 然后看到网上没有什么解决办法。
这里我是用的 “docxtemplater”: “^3.28.2”,
“docxtemplater-image-module-free”: “^1.1.1”,
bug一: 如果控制台报错显示is not a zip file 那就是你路径错了 不要怀疑 出错的地方应该是在
就是JSZipUtils这一行
bug二:版本不同出现的问题也不同,这插件还挺难搞的,我这里是亲测我这个版本可用的 vue是用的3.0 我试过3.5的版本 我换了3.5连字符串写入也不能用。
bug三:如果控制台出现getter only namespace 那就是你JSZipUtils的问题
最后也不废话了 贴上我的代码吧,
//
//这玩意还是得要的,不管你是不是base64的图片
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");
var that = this;
var tempUrl = "";
//存放图片
const str = [];
JSZipUtils.getBinaryContent("../../index.docx",(error,content) => {
if (error) {
throw error
}
//有图片的话,需加上下面这段代码
const zip = new PizZip(content); // 创建一个JSZip实例,内容为模板的内容
const doc = new docxtemplater();
//有图片的话,需加载图片处理模块
doc.loadZip(zip);
//如果有二维码图案
that.crud.data.forEach((ele,index) => {
let url = that.$refs["qrCodeUrl" + index][0].getElementsByTagName('img')[0].src; //这里是为了拿到动态渲染的src地址值
let name = that.$refs["qrCodeUrl" + index][0].innerText;
str.push({src: url,name:name })
console.log(name)
})
// console.log(str)
//图片处理
const opts = {}
opts.centered = false; //图片居中,在word模板中定义方式为{%image}
opts.fileType= "docx";
opts.getImage = (chartId) => {
return that.base64DataURLToArrayBuffer(chartId)
}
opts.getSize = () => {
return [100,100];
};
const imageModule = new ImageModule(opts);
doc.attachModule(imageModule);
doc.setData({images: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;
}
var out = doc.getZip().generate({
type:"blob",
mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(out, this.cplx.cpName + ".docx")
})
}
最后说一句 我这个代码是动态渲染的 dom 然后去拿的src值 有啥不明白的评论留言吧 虽然也有可能看不到 哈哈哈