导出word文件(word模板方式)

需求

导出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的加速域换成建桶的域中解决了跨域问题。

posted @ 2021-04-28 09:54  redRunZhy  阅读(2676)  评论(2编辑  收藏  举报