web生成word模板

288 阅读1分钟

依赖

"docxtemplater": "^3.43.1",
"docxtemplater-image-module-free": "^1.1.1",
"pizzip": "^3.1.4",

实现

import Docxtemplater from "docxtemplater";
import ImageModule from "docxtemplater-image-module-free";
import PizZip from 'pizzip';
import PizZipUtils from 'pizzip/utils/index.js';
 // 下载文件
async function downloadFile(from, fileName) {
    if (!(from instanceof Blob)) from = await (await fetch(from)).blob();
    const aEl = document.createElement('a');
    aEl.href = URL.createObjectURL(from);
    aEl.download = fileName || '';
    aEl.click();
}
// docx模板生成
async function docx(dcoxUrl, outName, data) {
    if (arguments.length < 3) throw new Error('docx方法缺少必要的参数');
    const response = await fetch(dcoxUrl);
    const arrayBuffer = await response.arrayBuffer();
    const zip = new PizZip(arrayBuffer);

    const imageModule = new ImageModule({
        centered: false,
        fileType: 'docx',
        getImage: async (tagPath) => (await fetch(tagPath)).arrayBuffer(),
        getSize(img) {
            return [150, 150];// ImageSize
        }
    });

    const doc = new Docxtemplater()
        .loadZip(zip)
        .attachModule(imageModule).compile()
        // .setData(data)
        .renderAsync(data)
    doc.then(() => {
        const out = doc.getZip().generate({
            type: 'blob',
            mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });
        downloadFile(out, outName);
    })
},

使用

docx('./文档.docx', '文档.docx', {
    name: "xx",
    info: { id: 1, address: [{ title: 'xxxx' },{ title: 'xxxx' }] },
    img: 'url'
})
    /** 标签
     * {#父对象名}{子属性}{/父对象名}
     * {属性名称}
     * {%图片路径}
     * 文档 https://docxtemplater.com/docs/tag-types/
     */

image.png

效果

image.png