docxtemplater + vue + docxtemplater-image-module-free 实现前端 word文字下载和免费图片下载

3,185 阅读3分钟

1.简介

docxtemplate是一个从docx/pptx模板生成docx/pptx文档的库。它可以用数据替换{占位符},还支持循环和条件。模板可以由非程序员编辑,例如您的客户端。 docxtemplate支持的功能很多,语法包含变量替换、条件判断、循环、列表循环、表格循环等,还包括图片、html等模块转换,详情见:docxtemplater.com/demo/

说白了,最好的一点是 word模板自己定义,格式上可以用word生成,还是非常棒的,贴个例子: word模板中的定义: 在这里插入图片描述 下载后的效果: 下载后的效果,可以看到定义的变量被替换为数据 可以看到,用占位符{}包裹的变量下载后被定义的数据替换了。

2.语法

2.1.替换

js中定义的变量:

{title:'简介',}

word模板文件中语法:

{title}

2.2.循环

js中定义的变量:

{
    loop:[
        { name: "Windows", price: 100},
        { name: "Mac OSX", price: 200 },
        { name: "Ubuntu", price: 0 }
    ],
    userGreeting: (scope) => {
         return "The product is" + scope.name + ", price:" + scope.price;
    },
}

word模板文件中语法:

循环{#loop} 
    {name}, {price}
    // 匿名函数插槽用法
    {userGreeting}
{/loop}

2.3.判断

js中定义的变量:

{
    hasKitty: true,
    kitty: "Minie",
    hasDog: false,
    dog: "wangwang",
}

word模板文件中语法:

	{#hasKitty}
		Cat’s name: {kitty}
	{/hasKitty} 
	{#hasDog}
		Dog’s name: {dog}
	{/hasDog}

2.4.图片

js中定义的变量:

{
    //文件路径
    image: '/logo.png',
}

word模板文件中语法:

{%image}

2.5.高级用法

需要安装插件:'angular-expressions' 、 'lodash' , 配置完成后,可使用判断高级语法等:

{#users.length>1} There are multiple users {/}
{#users[0] == 1} The first value is 1 {/}

深层取值语法:

{user.age}--{user.num.say}

3.在vue中使用

3.1普通用法(文字模板)

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import PizZipUtils from 'pizzip/utils/index.js'
import { saveAs } from 'file-saver'
function loadFile(url, callback) {
    PizZipUtils.getBinaryContent(url, callback)
}

methods: {
    renderImg() {
        loadFile('/word.docx',
        function(error, content) {
            if (error) {
                throw error
            }
            const zip = new PizZip(content)
            // options 是个对象 可自己配置
            const options = {
                    paragraphLoop: true,
                    linebreaks: true,
		}
            const doc = new Docxtemplater(zip, options)
            doc.render({
                products: [
                    { name: "Windows", price: 100 },
                    { name: "Mac OSX", price: 200 },
                    { name: "Ubuntu", price: 0 }
                ],
                userGreeting: (scope) => {
                    return "The product is" + scope.name;
                },
            })
            const out = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            })
            // Output the document using Data-URI
            saveAs(out, 'output1.docx')
    })
}

3.2添加免费图片插件

官方提供的图片下载模块是需要收费的,有爱心人士开发了不收费的插件'docxtemplater-image-module-free',那必须用起来啊:

import ImageModule from 'docxtemplater-image-module-free'

methods: {
    renderImg() {
        loadFile('/word.docx',
            function(error, content) {
                if (error) {
                    throw error
                }
		
            const imageOpts = {
            getImage: function(tagValue, tagName) {
                return new Promise(function (resolve, reject) {
                    PizZipUtils.getBinaryContent(tagValue, function (error, content) {
                        if (error) {
                            return reject(error);
                        }
                        return resolve(content);
                    });
                });
            },
            getSize : function (img, tagValue, tagName) {
                // FOR FIXED SIZE IMAGE :
                return [150, 150];
            }
        }
		
        var imageModule = new ImageModule(imageOpts);
        const zip = new PizZip(content)
        const doc = new Docxtemplater().loadZip(zip).setOptions({
            // delimiters: { start: "[[", end: "]]" },
            paragraphLoop: true,
            linebreaks: true,
        }).attachModule(imageModule).compile()
            doc.renderAsync({
                image: '/logo.png',
                title: '简介',
                ...
            }).then(function () {
                const out = doc.getZip().generate({
                    type: "blob",
                    mimeType: 'application/vnd.openxmlformatsofficedocument.wordprocessingml.document',
                });
                    saveAs(out, "generated.docx");
            });
        })
    }
}

3.3 添加解析语法

可以使用更多更便捷的word模板语法,见2.5节

import expressions from 'angular-expressions'
import assign from 'lodash/assign'
expressions.filters.lower = function (input) {
    // This condition should be used to make sure that if your input is
    // undefined, your output will be undefined as well and will not
    // throw an error
    if (!input) return input;
    return input.toLowerCase();
}

function angularParser(tag) {
    tag = tag
        .replace(/^\.$/, "this")
        .replace(/('|')/g, "'")
        .replace(/("|")/g, '"');
    const expr = expressions.compile(tag);
    return {
        get: function (scope, context) {
            let obj = {};
            const scopeList = context.scopeList;
            const num = context.num;
            for (let i = 0, len = num + 1; i < len; i++) {
                obj = assign(obj, scopeList[i]);
            }
            return expr(scope, obj);
        },
    };
}

new Docxtemplater().loadZip(zip).setOptions({parse: angularParser})

在vue中使用的示例代码已经放到github上面,地址链接:wordDown,有不清楚的小伙伴,欢迎留言讨论。