官网:https://docxtemplater.com/modules/image/
代码
import ImageModule from "docxtemplater-image-module-free";
图片为base64格式
//loadFile
function loadFile(url, callback) {
JSZipUtils.getBinaryContent(url, callback);
}
//imageOpts
const imageOpts = {
getImage: function (tagValue, tagName) {
console.log(tagValue, tagName);
const base64Value = base64Parser(tagValue);
console.log(base64Value);
if (base64Value) {
return base64Value;
}
// tagValue is "https://docxtemplater.com/xt-pro-white.png"
// tagName is "image"
},
getSize: function (img, tagValue, tagName) {
// img is the value that was returned by getImage
// This is to limit the width and height of the resulting image
const maxWidth = 200;
const maxHeight = 200;
const sizeOf = require("image-size");
const sizeObj = sizeOf(img);
const widthRatio = sizeObj.width / maxWidth;
const heightRatio = sizeObj.height / maxHeight;
if (widthRatio < 1 && heightRatio < 1) {
/*
* Do not scale up images that are
* smaller than maxWidth,maxHeight
*/
return [sizeObj.width, sizeObj.height];
}
let finalWidth, finalHeight;
if (widthRatio > heightRatio) {
/*
* Width will be equal to maxWidth
* because width is the most "limiting"
*/
finalWidth = maxWidth;
finalHeight = sizeObj.height / widthRatio;
} else {
/*
* Height will be equal to maxHeight
* because height is the most "limiting"
*/
finalHeight = maxHeight;
finalWidth = sizeObj.width / heightRatio;
}
return [Math.round(finalWidth), Math.round(finalHeight)];
},
getProps: function (img, tagValue, tagName) {
/*
* If you don't want to change the props
* for a given tagValue, you should write :
*
* return null;
*/
return {
align: "left",
};
},
};
//判断是否为base64
const base64Regex =
/^data:image\/(png|jpg|svg|svg\+xml);base64,/;
function base64Parser(dataURL) {
if (
typeof dataURL !== "string" ||
!base64Regex.test(dataURL)
) {
return false;
}
const stringBase64 = dataURL.replace(base64Regex, "");
// For nodejs
if (typeof Buffer !== "undefined" && Buffer.from) {
return Buffer.from(stringBase64, "base64");
}
// For browsers :
const binaryString = window.atob(stringBase64);
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;
}
加入图片模块
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
modules: [new ImageModule(imageOpts)],//图片模块
});
模版文档
使用{%image}标签