祖安之光
10 天以前 7df5ffa1db94e3225bd16ef2d0d8ef0e02084951
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
//引入工具
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
 
// 加载 .docx 模板文件
function loadFile(url, callback) {
    JSZipUtils.getBinaryContent(url, callback);
}
 
// 下载生成的文档
export function download(file, name) {
 
}
 
// 生成并下载 Word 文档(templatePath是word文档模版地址,data是对应的数据)
export function generateWordDocument(templatePath, data, name) {
        loadFile(templatePath, function (error, content) {
            if (error) {
                throw error
                return;
            }
 
            try {
                // 加载模板文件内容到 PizZip
                const zip = new PizZip(content);
                const doc = new Docxtemplater(zip, {
                    paragraphLoop: true,
                    linebreaks: true,
                });
 
                // 设置模板中的占位符数据
                doc.setData(data);
 
                // 渲染文档
                doc.render();
 
                // 生成最终的文档 Blob
                const fileWord = doc.getZip().generate({
                    type: 'blob',
                    mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                });
 
                saveAs(fileWord, name);
 
                // // 返回生成的文档 Blob
                // resolve(fileWord);
            } catch (error) {
                console.error('Error rendering document:', error);
                throw error
            }
        });
 
}