【word导出带图片】使用docxtemplater导出word,通知书形式的word

2024-09-04 05:44

本文主要是介绍【word导出带图片】使用docxtemplater导出word,通知书形式的word,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、demo-导出的的

二、代码操作

1、页面呈现

项目要求,所以页面和导出来的word模版一致

2、js代码【直接展示点击导出的js代码】

使用插件【先下载这五个插件,然后页面引入插件】

import docxtemplater from 'docxtemplater'

import PizZip from 'pizzip'

import JSZipUtils from 'jszip-utils'

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

import { saveAs } from 'file-saver'

 1>代码

    expeortexcel() {clearTimeout(this.timer) //清除延迟执行this.faultlist = []this.faultpic = []const exportData = this.data// 处理图片const crfile = exportData.contractorResponsiblePerson[0].linkconst drfile = exportData.drawResponsiblePerson[0].linkif (crfile != '') {this.UrlToBase64(crfile, (dataURL) => {exportData['crimg'] = dataURL})}if (drfile != '') {this.UrlToBase64(drfile, (dataURL) => {exportData['drimg'] = dataURL})}this.faultlist.push(exportData)this.timer = setTimeout(() => {//设置延迟执行this.export2Word(this.faultlist)}, 5000)},
// 处理导出图片数据UrlToBase64(url, callback) {console.log(url, 'url===')let image = new Image()let that = this//解决跨域问题image.setAttribute('crossOrigin', 'anonymous')image.src = urlimage.onload = () => {var canvas = document.createElement('canvas')canvas.width = image.widthcanvas.height = image.heightvar context = canvas.getContext('2d')context.drawImage(image, 0, 0, image.width, image.height)var quality = 0.8//这里的dataurl就是base64类型var dataURL = canvas.toDataURL('image/png', quality)callback ? callback(dataURL) : null //调用回调函数}},//导出文件export2Word(faultlistd) {//v:图片路径,t:时间字符串,name:导出文件名称--变量需自己定制,此处为举例let self = thisJSZipUtils.getBinaryContent(window.location.origin + '/tinggong.docx', //需要导出的模板文件地址function (error, content) {if (error) {throw error}let zip = new PizZip(content)let doc = new docxtemplater().loadZip(zip)// 图片处理const opts = {}opts.centered = false // 图片居中,在word模板中定义方式为{%image}opts.fileType = 'docx'opts.getImage = (tagValue, tagName) => {const base64Value = self.base64DataURLToArrayBuffer(tagValue)if (base64Value) {return base64Value}}opts.getSize = function (img, tagValue, tagName) {const sizeOf = require('image-size')const buffer = Buffer.from(img, 'binary')const sizeObj = sizeOf(buffer)const forceWidth = 100const ratio = forceWidth / sizeObj.widthreturn [forceWidth, Math.round(sizeObj.height * ratio)]}let imageModule = new ImageModule(opts)doc.attachModule(imageModule)setTimeout(() => {doc.setData({//设置模板数据// compname: cname,listfa: faultlistd,// listimg: faultpicd,})try {doc.render()} catch (error) {let e = {message: error.message,name: error.name,stack: error.stack,properties: error.properties,}console.log(JSON.stringify({ error: e }))throw error}let out = doc.getZip().generate({type: 'blob',mimeType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document', //导出文件格式})saveAs(out, '停工通知书.docx')}, 4000)},)},//获取base64格式图片base64DataURLToArrayBuffer(dataURL) {const base64Regex = /^data:image\/(png|jpg|svg|svg);base64,/if (!base64Regex.test(dataURL)) {return false}const stringBase64 = dataURL.replace(base64Regex, '')let binaryStringif (typeof window !== 'undefined') {binaryString = window.atob(stringBase64)} else {binaryString = Buffer.from(stringBase64, 'base64').toString('binary')}const len = binaryString.lengthconst bytes = new Uint8Array(len)for (let i = 0; i < len; i++) {const ascii = binaryString.charCodeAt(i)bytes[i] = ascii}return bytes.buffer},

1、this.data是接口返回的数据

2、UrlToBase64处理图片数据

3、export2Word导出文件操作

三、通知书模版【毕竟放在public下-且后缀是.docx】 

【语法:】

listfa是数组,#开头, /结束     

{%drimg}   图片格式前面需要加%

四、拓展docxtemplater语法

官网:Docxtemplater | Word, Powerpoint, Excel generation using templates in your application | docxtemplater

1、基础

       Hello {name} !   //  得到 —— Hello John !


     

{"name": "John"}  // 数据格式

2、条件  开始    结束

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

{"hasKitty": true,"kitty": "Minie""hasDog": false,"dog": null
}// 得到Cat’s name: Minie

3、list集合

{#products}
{name}, {price} ¥
{/products}

 "products": [{ "name": "西服外套", "price": 100 },{ "name": "皮鞋", "price": 200 },{ "name": "劳动力", "price": 0 }]// 得到 西服外套, 100 ¥皮鞋, 200 ¥劳动力, 0¥

4、循环遍历一个包含原始数据的数组

{#products} {.} {/products}

 "products": ["包子", "饺子", "麻辣烫"]// 得到 包子 饺子 麻辣烫

5、循环展示列表【#开头   /结束】

        Nameagephone
{#users}{name}{age}{phone}{/}
 

 

"users": [{ "name": "John", "age": 22, "phone": "+33653454343" },{ "name": "Mary", "age": 25, "phone": "+33666666666" }]

得到:

 Nameagephone
John22+33653454343
Mary25+33666666666

这篇关于【word导出带图片】使用docxtemplater导出word,通知书形式的word的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1135164

相关文章

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语