docxtemplater避坑!!! 前端导出word怎么插入本地图片或base64 有完整示例

docxtemplater库实现前端通过模板导出word,遇到需求,要插图片并转成word并导出,在图片转换这块遇到了问题,网上查示例大多都跑不通,自己琢磨半天,总算搞明白了。

附上清晰完整示例,供参考。

如有不懂,私我询问!

首先需要一个word文件作为模板test.docx

必须是docx文件!!!

{%} 代表图片 xgq是变量

安装需要的包

npm install docxtemplater
npm install docxtemplater-image-module-free
npm install pizzip
npm install file-saver
npm install html2canvas # 如需截图的话 安装
import Docxtemplater from 'docxtemplater';
import { saveAs } from 'file-saver';
import PizZip from 'pizzip';
import ImageModule from 'docxtemplater-image-module-free';
import html2canvas from 'html2canvas';
import image from './20240522152640.jpg';
import docx from './test.docx';

插入本地图片并转换

const imageData = await fetch(image);
const imageArrayBuffer = await imageData.arrayBuffer();
const imgDataDict: Record<string, ArrayBuffer> = {xgq: imageArrayBuffer,
};
const docxData = await fetch(docx);
const docxArrayBuffer = await docxData.arrayBuffer();
const zip = new PizZip(docxArrayBuffer);
const doc = new Docxtemplater(zip, {paragraphLoop: true,linebreaks: true,modules: [new ImageModule({getImage: (value: string, key: string) => {return imgDataDict[key];},getSize: (afterValue: ArrayBuffer, value: string, key: string) => {return [400, 400];},}),],
});
doc.render({xgq: "xgq", // 这里得是字符串否则会报错
});
const blob = doc.getZip().generate({type: "blob",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(blob, "download.docx");

插入base64图片并转换

const base64 ="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAzKADAAQAAAABAAAAvAAAAAD/4gIQSUNDX1BST0ZJTEUAAQEAAAIAYXBwbAQAAABtbnRyUkdCIFhZWiAH6AAFABYADQABACJhY3NwQVBQTAAAAABBUFBMAAAAAAAAAAAAAAAAAAAAAAAA9tYAAQAAAADTLWFwcGyUGWuT9Z12r6yIp8KqjC97A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xpwbjkUc+lFZKn3KjC2ou72pm406iqdLsOUbjdxxTetPyKaTWMqeppFWRHkmk3EUu40xjk1KQ2ITk5pm40jH0pj8CqSBRB3INM3mmZzRT5SuU//9L51mPaq2KsS9RUOBX9JyjqfgyK7KcVCQR1q03SoJOorP2Yyq0bFiajKkDNWqiIyMUcqAgqMoSc1MwA6U2sZLUCn5bUxk9avkZGKjMYPc1j7PsNFEqQOKhAY1bbhitDIoHFDTLXmUmU55puPappOCMUDlaVmPmfQgIJpu01KRim1nJaBGd2R0hGak2ikIxWfKaXItppKkppArKUNSkQlc9DTSpFTYFIVBrHkL5SpTX6VKygE1GRkYrSEUawiiH8aPxpWAHSm1fIi+RH/9k=";
const imageArrayBuffer = base64DataURLToArrayBuffer(base64);
const imgDataDict: Record<string, ArrayBuffer> = {xgq: imageArrayBuffer,
};
const docxData = await fetch(docx);
const docxArrayBuffer = await docxData.arrayBuffer();
const zip = new PizZip(docxArrayBuffer);
const doc = new Docxtemplater(zip, {paragraphLoop: true,linebreaks: true,modules: [new ImageModule({getImage: (value: string, key: string) => {return imgDataDict[key];},getSize: (afterValue: ArrayBuffer, value: string, key: string) => {return [400, 400];},}),],
});
doc.render({xgq: "xgq", // 这里得是字符串否则会报错
});
const blob = doc.getZip().generate({type: "blob",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(blob, "download.docx");
const base64DataURLToArrayBuffer = (dataURL: string) => {const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;if (!base64Regex.test(dataURL)) {return false;}const stringBase64 = dataURL.replace(base64Regex, "");let binaryString;if (typeof window !== "undefined") {binaryString = window.atob(stringBase64);} else {binaryString = new Buffer(stringBase64, "base64").toString("binary");}const len = binaryString.length;const bytes = new Uint8Array(len);for (let i = 0; i < len; i++) {const ascii = binaryString.charCodeAt(i);bytes[i] = ascii;}return bytes.buffer;
};

截图某个网页区域并插入转换

<div id="test" style={{ border: "1px solid red", width: 300 }}><div>截图</div><button type="button">666</button><br /><img src={image} />
</div>;
const dom: any = document.getElementById("test");
const canvas = await html2canvas(dom, {useCORS: true,scale: 5,
});
const imageDataURL = canvas.toDataURL("image/png");
const response = await fetch(imageDataURL);
const imageArrayBuffer = await response.arrayBuffer();
const imgDataDict: Record<string, ArrayBuffer> = {xgq: imageArrayBuffer,
};
const docxData = await fetch(docx);
const docxArrayBuffer = await docxData.arrayBuffer();
const zip = new PizZip(docxArrayBuffer);
const doc = new Docxtemplater(zip, {paragraphLoop: true,linebreaks: true,modules: [new ImageModule({getImage: (value: string, key: string) => {return imgDataDict[key];},getSize: (afterValue: ArrayBuffer, value: string, key: string) => {return [400, 400];},}),],
});
doc.render({xgq: "xgq", // 这里得是字符串否则会报错
});
const blob = doc.getZip().generate({type: "blob",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(blob, "download.docx");

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/840679.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SpringCloudAlibaba:6.2RocketMQ的普通消息的使用

简介 普通消息也叫并发消息&#xff0c;是发送效率最高&#xff0c;使用最多的一种 依赖 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSch…

【强化学习的数学原理-赵世钰】课程笔记(三)贝尔曼最优公式

目录 学习引用内容梗概1. 第三章主要有两个内容2. 第二章大纲 二.激励性实例&#xff08;Motivating examples&#xff09;三.最优策略&#xff08;optimal policy&#xff09;的定义四.贝尔曼最优公式&#xff08;BOE&#xff09;&#xff1a;简介五.贝尔曼最优公式&#xff0…

专为汽车内容打造的智能剪辑解决方案

汽车内容创作已成为越来越多车主和汽车爱好者热衷的活动。然而&#xff0c;如何高效、便捷地将行车途中的精彩瞬间转化为高质量的视频作品&#xff0c;一直是困扰着广大用户的一大难题。美摄科技凭借其深厚的视频处理技术和智能分析能力&#xff0c;推出了专为汽车内容记录而生…

C语言数据结构栈的概念及结构、栈的实现、栈的初始化、销毁栈、入栈、出栈、检查是否为空、获取栈顶元素、获取有效元素个数等的介绍

文章目录 前言栈的概念及结构栈的实现一、 栈结构创建二、 初始化结构三、销毁栈四、入栈五、出栈六、检查是否为空七、获取栈顶元素八、获取有效元素的个数九、测试 1十、测试 2总结 前言 C语言数据结构栈的概念及结构、栈的实现、栈的初始化、销毁栈、入栈、出栈、检查是否为…

意外发现openGauss兼容Oracle的几个条件表达式

意外发现openGauss兼容Oracle的几个条件表达式 最近工作中发现openGauss在兼容oracle模式下&#xff0c;可以兼容常用的两个表达式&#xff0c;因此就随手测试了一下。 查看数据库版本 [ommopenGauss ~]$ gsql -r gsql ((openGauss 6.0.0-RC1 build ed7f8e37) compiled at 2…

数据结构----堆的实现(附代码)

当大家看了鄙人的上一篇博客栈后&#xff0c;稍微猜一下应该知道鄙人下一篇想写的博客就是堆了吧。毕竟堆栈在C语言中常常是一起出现的。那么堆是什么&#xff0c;是如何实现的嘞。接下来我就带大家去尝试实现一下堆。 堆的含义 首先我们要写出一个堆&#xff0c;那么我们就需…

kubernetes之prometheus kube-controller-manager。 scheduler报错问题

项目场景&#xff1a; prometheus scheduler及kube-controller-manager监控报错 问题描述 kubeadm搭建完kube-prometheus 会有这个报错 原因分析&#xff1a; rootmaster2:~# kubectl describe servicemonitor -n kube-system kube-controller-manager通过以上图片我们发现 k…

php TP8 阿里云短信服务SDKV 2.0

安装&#xff1a;composer require alibabacloud/dysmsapi-20170525 2.0.24 官方文档&#xff1a;短信服务_SDK中心-阿里云OpenAPI开发者门户 (aliyun.com) 特别注意&#xff1a;传入参数获得值形式 正确&#xff1a; $PhoneNumbers $postData[PhoneNumbers];$signName $po…

单片机设计注意事项

1.电源线可以30mil走线&#xff0c;信号线可以6mil走线 2.LDO推荐 SGM2019-3.3,RT9013,RT9193,1117-3.3V。 3.单片机VCC要充分滤波后再供电&#xff0c;可以接0.1uf的电容 4.晶振附件不要走其他元件&#xff0c;且放置完单片机后就放置晶振&#xff0c;晶振靠近X1,X2。

【全网最全】2024电工杯数学建模A题前三题完整解答matlab+21页初步参考论文+py代码等(后续会更新成品论文)

您的点赞收藏是我继续更新的最大动力&#xff01; 一定要点击如下的卡片链接&#xff0c;那是获取资料的入口&#xff01; 【全网最全】2024电工杯数学建模A题前三题完整解答matlab21页初步参考论文py代码等&#xff08;后续会更新成品论文&#xff09;「首先来看看目前已有的…

二叉树—先后序线索化和先后序线索遍历

有了上篇文章的基础&#xff0c;先序和后序的线索化逻辑一样。 代码如下&#xff1a; void preOrderThreadTree(TreeNode* T,TreeNode** pre) {if (T NULL) {;}else {//printf("%c ", T->val);if (T->lchild NULL) {T->ltag 1;T->lchild *pre;}if …

7款好用到离谱的神级App推荐!

AI视频生成&#xff1a;小说文案智能分镜智能识别角色和场景批量Ai绘图自动配音添加音乐一键合成视频https://aitools.jurilu.com/ 转眼间&#xff0c;2024年已经是下个月。最近有很多小伙伴的咨询&#xff0c;我也赶紧整理了7款好用的软件&#xff0c;希望对大家有所帮助。 …

Git简介以及下载安装和配置

Git介绍 什么是版本控制?什么是Git?什么是集中式版本控制(了解)分布式版本控制工作流程 Git的安装与配置注册邮箱以及用户名(方便远程使用)初始化项目Git在ideal上的使用(本地) 什么是版本控制? ​ 版本控制是指对软件开发过程中各种程序代码,控制文件及说明文档等文件变更…

清理mysql binglog文件

mysql随着使用时间的推移&#xff0c;binglog文件会越来越大&#xff0c;比如我们的oa系统&#xff0c;上线4年多了&#xff0c;最近总有磁盘空间满影响系统正常使用的情况出现。检查后发现binglog是罪归祸首。 binglog文件最好不要采用应删除的方式清理&#xff0c;如下方式可…

spring cache(三)demo

一、入门demo 1、pom <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.o…

ACL组网实验(华为)

思科设备参考&#xff1a;ACL组网实验&#xff08;思科&#xff09; 更多内容参考&#xff1a;华为ACL配置&#xff08;基本ACL高级ACL综合应用&#xff09; 技术简介 ACL&#xff08;Access Control List&#xff09;技术是一种基于包过滤的流控制技术&#xff0c;主要用于…

ML307R OpenCPU UART使用

一、串口使用流程图 二、串口相关函数介绍 三、实现串口收发 一、串口使用流程图 OneMO ML307R模组提供了2路UART给开发者用于通讯开发&#xff0c;以及1路DBG UART用于log的打印。UART Demo示例可以在SDK&#xff1a;examples\uart\src\cm_demo_uart.c中查看。 串口使用流…

Vue3实战笔记(42)—Vue + ECharts:流量数据可视化的强大组合

文章目录 前言vue3使用echarts标准demo&#xff1a;总结 前言 在前端开发中&#xff0c;数据可视化已经成为了一个不可或缺的部分。Vue.js作为一个轻量级且易于上手的渐进式JavaScript框架&#xff0c;与ECharts这个强大的数据可视化库的结合&#xff0c;使得在Vue应用中构建交…

java继承(构造器)使用细节3

那么我们怎么来选择用父类的 有参构造器 和无参构造器泥&#xff1f; 就可以不写 或只写super() 并且如像爸爸的爸爸还有爸爸&#xff0c;还有构造。所以会一直调用到爷爷的构造。 细节2 直接继承指的是儿子和爸爸&#xff0c;爸爸和爷爷