kongdeqiang
2023-06-08 f015ecea67a1e322374c422f6661366f93341556
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
let docx = require("docx-preview");
const ImageModule = require("docxtemplater-image-module-free");
 
//下载word,不带图片
export const exportDoc = (e,path,dname) => {
  for(let i in e) {
    if(e[i] == null) {
      e[i] = ''
    }
  }
  let docxsrc = path;        //模板文件的位置
  let docxname = dname;        //导出文件的名字
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(docxsrc,function (error, content) {
    if (error) throw error // 抛出异常
    let zip = new PizZip(content) // 创建一个JSZip实例,内容为模板的内容
    let doc = new docxtemplater().loadZip(zip) // 创建并加载docxtemplater实例对象
    doc.setData(e)  // 设置模板变量的值
    try {
      doc.render() // 用模板变量的值替换所有模板变量
    } catch(error) {
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      }
      console.log(JSON.stringify({ error: e }))
      throw error // 抛出异常
    }
    // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    });
    // 将目标文件对象保存为目标类型的文件,并命名
    saveAs(out, docxname);
  })
}
 
//预览word,不带图片的
export const viewD = (e, path , continer) => {
  for (let attr in e) {
    if (e[attr] == null) {
      e[attr] = "";
    }
  }
  let docxsrc = path;        //模板文件的位置
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(docxsrc, function (error, content) {
    // docxsrc是模板。我们在导出的时候,会根据此模板来导出对应的数据
    // 抛出异常
    if (error) {
      throw error;
    }
 
    // 创建一个PizZip实例,内容为模板的内容
    let zip = new PizZip(content);
    // 创建并加载docx templater实例对象
    let doc = new docxtemplater().loadZip(zip);
    // 设置模板变量的值
    doc.setData(e);
 
    try {
      //替换所有模板变量
      doc.render();
    } catch (error) {
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      };
      console.log(JSON.stringify({error: e}));
      throw error;
    }
 
    // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    });
    docx.renderAsync(out, continer); // 渲染到页面预览
  });
};