需求
導出word文件,需要導出圖片
第三方插件
以下插件npm下載方式:npm install XXX(對應以下插件的名字)
1、docxtemplater:這個插件可以通過預先寫好的word,excel等文件模板生成對應帶數據的文件
2、pizzip:這個插件用來創建,讀取或編輯.zip的文件(同步的,還有一個插件是jszip,異步的)
3、jszip-utils:與jszip/pizzip一起使用
4、file-saver:保存文件
5、docxtemplater-image-module-free:需要導出圖片的話需要這個插件
實現
1、doc模板文件放在public文件夾下

2、doc模板文件:(和代碼數據不一致,借鑒的別人博客的圖,僅展示模板寫法)

// 引入插件 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"; //需要導出的數據 form: { name: "****", // 普通數據 pics: [ // 圖片列表 { pic: "****", }, { pic: "****", }, { pic: "****", }, ], table: [{id:1, name:'****',age:'****'}], // 表格數據 }, // 導出word方法 let _this = this; JSZipUtils.getBinaryContent("doc文件路徑", function (error, content) { if (error) { console.error(error); return; } var opts = {}; opts.centered = false; opts.getImage = function (tagValue) { return new Promise(function (resolve, reject) { JSZipUtils.getBinaryContent(tagValue, function (error, content) { if (error) { return reject(error); } return resolve(content); }); }); }; //圖片有關代碼,沒有圖片的可以刪除 opts.getSize = function (img, tagValue, tagName) { return [150, 150]; //圖片大小 (固定的) // 非固定(這里是設置寬度最大為300px的圖片) return new Promise(function (resolve, reject) { var image = new Image(); image.src = tagValue; let imgWidth, imgHeight, scale; image.onload = function () { imgWidth = image.width; imgHeight = image.height; scale = 0; if (imgWidth > 300) { scale = 300 / imgWidth; imgWidth = 300; imgHeight = imgHeight * scale; } resolve([imgWidth, imgHeight]); }; image.onerror = function (e) { console.log("img, tagValue, tagName : ", img, tagValue, tagName); reject(e); }; }); }; var imageModule = new ImageModule(opts); var zip = new PizZip(content); var doc = new docxtemplater() .loadZip(zip) .attachModule(imageModule) .compile(); doc .resolveData(需要導出的數據對象,對應上面的form) .then(function () { console.log("ready"); doc.render(); var out = doc.getZip().generate({ type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", }); //輸出文檔 saveAs(out, "自定義輸出的文件名.docx"); }); });
tips
有個問題是,我請求的圖片是oss的圖片,報跨域問題,但是瀏覽器f12的network選中disable cache就正常了(沒有找到原因)。然后把oss的加速域換成建桶的域中解決了跨域問題。
