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

1.简介

docxtemplate是一个从docx/pptx模板生成docx/pptx文档的库。它可以用数据替换{占位符},还支持循环和条件。模板可以由非程序员编辑,例如您的客户端。
docxtemplate支持的功能很多,语法包含变量替换、条件判断、循环、列表循环、表格循环等,还包括图片、html等模块转换,详情见:https://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’ ,
配置完成后,可在word模板中使用判断高级语法等:

	{#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,有不清楚的小伙伴,欢迎留言讨论。

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值