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

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

  1. vue实现图片下载功能so easy

    vue实现图片下载功能so easy 1.在前端实现图片下载分为同源图片下载和非同源图片下载 2.解决方案可以根据同源和非同源来制定 同源图片下载方案 html中可以这样写 <a href=&q ...

  2. vue + docxtemplater 实现前端生成并下载word

    vue + docxtemplater 实现前端生成并下载word 文章目录 vue + docxtemplater 实现前端生成并下载word 前言 平时工作中需要将多条数据以word形式下载,手动 ...

  3. vue+docxtemplater,填充word模板

    安装依赖 yarn add docxtemplateryarn add pizzipyarn add jszip-utilsyarn add file-saver// 模板解析插件(支持list循环直 ...

  4. vue+docxtemplater实现读取word文档,根据后端数据生成echarts图表插入word,并下载为docx格式文件

    一.需求 word自带的图表不能满足需求,并且编写过程繁琐,需要写一个页面,主要功能是能读取服务器的word模板,根据后台给的数据,自动生成echarts图表并插入到word指定位置,然后点击能下载插 ...

  5. Vue入门之Web端CURD前端项目示例

    Vue入门之Web端CURD前端项目示例 随着vue.js越来越火,很多不太懂前端的小伙伴想要入坑.而入坑最好的办法就是上手实际操作,因此本文将重点放在实际操作上,对理论不做过多解释,不明白的地方小伙 ...

  6. vue前端用服务器上路径的图片展示_5分钟教你用nodeJS手写一个mock数据服务器

    对于前端开发者而言,javascript正扮演着越来越重要的地位,它不仅能为浏览器端赋能,在web服务器方面也有很大的价值(我们可以用nodeJS来写服务端代码,启动web服务器),因此本文所要描述的 ...

  7. element ui 前台模板_SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(二):引入 element-ui 定义基本页面显示...

    前提: (1) 相关博文地址: SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(一):搭建基本环境:https://www.cnblogs.com/l-y ...

  8. Vue报错Module build failed Error Node Sass version 6.0.1 is incompatible with ^4.0.0.解决方案

    Vue报错Module build failed: Error: Node Sass version 6.0.1 is incompatible with ^4.0.0.解决方案 错误提示: ERRO ...

  9. vue项目落地(qiankun.js)微前端服务

    什么是微前端? 网上抄的: 微前端是一种类似于微服务的架构,它将微服务的理念应用于浏览器端,即将单页面前端应用由单一的单体应用转变为多个小型前端应用聚合为一的应用.各个前端应用还可以独立开发.独立部署 ...

最新文章

  1. mysql 命令行小结
  2. 原来这样做运维,就可以不被 KO丨课程推广
  3. Spring Boot Actuator
  4. java使用POI工具类导出excel
  5. Android笔记 解析xml文件demo
  6. kafka : CommitFailedException already rebalanced and assigned max.poll.records
  7. linux vi 查找哈希,利用 Hashtable 实现快速查找比较-了解
  8. 使用 MTR 分析网络延迟及丢包
  9. 在Android应用中集成YouTube视频播放功能
  10. 计算机课英语怎么读音标,英语的48个音标有哪些?英语的48个音标怎么读?
  11. 2012第35周国内Android应用下载动态
  12. 小白学语句:省市区选择(带全国省市区数据)
  13. 一元多项式的相加和相减操作(链表)
  14. 【Trailing spaces not allowed no-trailing-spaces】报错
  15. 2021-11-12每日刷题打卡
  16. unity 构建迷宫_教程:使用GameDraw在Unity中构建迷宫游戏关卡
  17. linux 安装插件报错:Loaded plugins: fastestmirror
  18. python基础编程
  19. python制作翻译小软件_如何基于Python制作有道翻译小工具
  20. Python的traceback

热门文章

  1. 将服务器安装为域控制器
  2. 力扣 1816. 截断句子
  3. 【Android初级面筋】在这个要求高级开发的行情下,初级开发者怎样在面试中杀出重围?
  4. pcie link training
  5. python判断成语类型_Python成语返回第一项或None
  6. 在Ubuntu18中安装Xen
  7. springboot+vue 课程在线考试系统 java
  8. 为什么程序员不自己单干?
  9. 国家二级心理咨询师_百度百科
  10. 【极客技术】啥?公众号免费开放ChatGPT Plus了?