# @chax-at/docxtemplater-image-module-free 中文文档

规范地址：https://npmcn.com/package/%40chax-at/docxtemplater-image-module-free/

版本：2\.0\.0
npm 元数据更新时间：2026-06-30T12:35:11.742Z
中文译文更新时间：2026-11-09T13:31:10.344Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40chax-at/docxtemplater-image-module-free
原文对照：https://npmcn.com/package/%40chax-at/docxtemplater-image-module-free/?lang=original
项目主页：https://github.com/chax-at/docxtemplater-image-module-free#readme
源码仓库：https://github.com/chax-at/docxtemplater-image-module-free

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：362 kB，16 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- 运行依赖：1 个
- 首次发布：2026-06-30T12:35:11.182Z
- 最新版本发布：2026-06-30T12:35:11.463Z
- 近 30 天下载量：2545（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 1 个）

## 中文简介

Docxtempter 的开源图像模块

## 安装

```sh
npm install @chax-at/docxtemplater-image-module-free
```

也可以使用：`pnpm add @chax-at/docxtemplater-image-module-free`、`yarn add @chax-at/docxtemplater-image-module-free`、`bun add @chax-at/docxtemplater-image-module-free`

## README

# 打开源代码临时图像模块

此寄存器持有一个forked chax-at版本 docxtemter后期图像模块.

此软件包是开源的 。 还有一个 [付费版本](https://docxtemplater.com/modules/image/) 由 docxtemplate 作者维护.

注意此版本与 docxtemplate 3.x相容.

## 安装

您首先需要安装 docxtimpter, 方法是跟踪它 [安装指南](https://docxtemplater.readthedocs.io/en/latest/installation.html)。 。 。 .

对于Node.js安装此软件包:

```bash
npm install docxtemplater-image-module-free
```

对于浏览器查找构建于 `build/` 目录.

或者,您可以从以下来源创建自己的建筑:

```bash
npm run compile
npm run browserify
npm run uglify
```

## 使用量

假设你 **docx 文档** 或者说 **页:1** 模板只包含文本 `{%image}`数字 :

```javascript
//Node.js example
var ImageModule = require('open-docxtemplater-image-module');

//Below the options that will be passed to ImageModule instance
var opts = {}
opts.centered = false; //Set to true to always center images
opts.fileType = "docx"; //Or pptx

//Pass your image loader
opts.getImage = function(tagValue, tagName) {
    //tagValue is 'examples/image.png'
    //tagName is 'image'
    return fs.readFileSync(tagValue);
}

//Pass the function that return image size
opts.getSize = function(img, tagValue, tagName) {
    //img is the image returned by opts.getImage()
    //tagValue is 'examples/image.png'
    //tagName is 'image'
    //tip: you can use node module 'image-size' here
    return [150, 150];
}

var imageModule = new ImageModule(opts);

var zip = new JSZip(content);
var doc = new Docxtemplater()
    .attachModule(imageModule)
    .loadZip(zip)
    .setData({image: 'examples/image.png'})
    .render();

var buffer = doc
        .getZip()
        .generate({type:"nodebuffer"});

fs.writeFile("test.docx",buffer);
```

关于模板的一些说明:

-   **docx 文档** 文件: 占位符 `{%image}` 必须是专门段落.
-   **页:1** 文件: 占位符 `{%image}` 必须在指定的文本单元格中.

在浏览器中, 显示如何同步实现图像 :

```html
<html>
<script src="node_modules/docxtemplater/build/docxtemplater.js"></script>
<script src="node_modules/jszip/dist/jszip.js"></script>
<script src="node_modules/jszip/vendor/FileSaver.js"></script>
<script src="node_modules/jszip-utils/dist/jszip-utils.js"></script>
<script src="build/imagemodule.js"></script>
<script>
  JSZipUtils.getBinaryContent('examples/image-example.docx', function (error, content) {
    if (error) {
      console.error(error);
      return;
    }
    var opts = {}
    opts.centered = false;
    opts.getImage = function (tagValue, tagName) {
      return new Promise(function (resolve, reject) {
        JSZipUtils.getBinaryContent(tagValue, function (error, content) {
          if (error) {
            return reject(error);
          }
          return resolve(content);
        });
      });
    }
    opts.getSize = function (img, tagValue, tagName) {
      // FOR FIXED SIZE IMAGE :
      return [150, 150];

      // FOR IMAGE COMING FROM A URL (IF TAGVALUE IS AN ADRESS) :
      // To use this feature, you have to be using docxtemplater async
      // (if you are calling setData(), you are not using async).
      return new Promise(function (resolve, reject) {
        var image = new Image();
        image.src = url;
        image.onload = function () {
          resolve([image.width, image.height]);
        };
        image.onerror = function (e) {
          console.log('img, tagValue, tagName : ', img, tagValue, tagName);
          alert("An error occured while loading " + tagValue);
          reject(e);
        }
      });
    }

    var imageModule = new ImageModule(opts);

    var zip = new JSZip(content);
    var doc = new docxtemplater()
      .loadZip(zip)
      .attachModule(imageModule)
      .compile();

    doc.resolveData({
      image: 'examples/image.png'
    }).then(function () {
      console.log('ready');
      doc.render();
      var out = doc.getZip().generate({
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      saveAs(out, "generated.docx");
    })
  });
</script>

</html>
```

## 居中图像

您可以通过设置全局切换为真来居中所有图像 `opts.centered = true`。 。 。 .

如果您要选择哪个图像应逐一居中:

-   设置全局切换为假 `opts.centered = false`。 。 。 .
-   使用 `{%image}` 对于不应该被集中的图像.
-   使用 `{%%image}` 用于您想要看到的图像.

单位 **页:1** 生成的文档,图像相对母单元格垂直和水平地居中.

## 同步支持

在获取图像函数中返回一个承诺并使用 docxtimpter async api 以同步方式获取图像是可能的 : [http://docxtemplater.readthedocs.io/en/latest/async.html 页面存档备份,存于互联网档案馆](http://docxtemplater.readthedocs.io/en/latest/async.html)

如果您想要同步解决大小( 如上面的浏览器示例) , 您也可以返回在 getSize 函数中的承诺 .

以下是节点中的一个例子,它允许您从 URL 中获取值并使用固定宽度, 并保持宽度比 .

```js
const fs = require("fs");
const DocxTemplater = require("docxtemplater");
const https = require("https");
const Stream = require("stream").Transform;

const ImageModule = require("./es6");
const JSZip = require("jszip");

const content = fs.readFileSync("demo_template.docx");

const data = {
  image: "https://docxtemplater.com/xt-pro.png"
};

const opts = {};
opts.getImage = function (tagValue, tagName) {
  console.log(tagValue, tagName);
  // tagValue is "https://docxtemplater.com/xt-pro-white.png" and tagName is "image"
  return new Promise(function (resolve, reject) {
    getHttpData(tagValue, function (err, data) {
      if (err) {
        return reject(err);
      }
      resolve(data);
    });
  });
};

opts.getSize = function (img, tagValue, tagName) {
  console.log(tagValue, tagName);
  // img is the value that was returned by getImage
  // This is to force the width to 600px, but keep the same aspect ration
  const sizeOf = require("image-size");
  const sizeObj = sizeOf(img);
  console.log(sizeObj);
  const forceWidth = 600;
  const ratio = forceWidth / sizeObj.width;
  return [
    forceWidth,
    // calculate height taking into account aspect ratio
    Math.round(sizeObj.height * ratio),
  ];
};

const imageModule = new ImageModule(opts);

const zip = new JSZip(content);
const doc = new DocxTemplater()
  .loadZip(zip)
  .attachModule(imageModule)
  .compile();

doc
  .resolveData(data)
  .then(function () {
    console.log("data resolved");
    doc.render();
    const buffer = doc
      .getZip()
      .generate({
        type: "nodebuffer",
        compression: "DEFLATE"
      });

    fs.writeFileSync("test.docx", buffer);
    console.log("rendered");
  })
  .catch(function (error) {
    console.log("An error occured", error);
  });

function getHttpData(url, callback) {
  https
    .request(url, function (response) {
      if (response.statusCode !== 200) {
        return callback(
          new Error(
            `Request to ${url} failed, status code: ${response.statusCode}`
          )
        );
      }

      const data = new Stream();
      response.on("data", function (chunk) {
        data.push(chunk);
      });
      response.on("end", function () {
        callback(null, data.read());
      });
      response.on("error", function (e) {
        callback(e);
      });
    })
    .end();
}
```

## 基于占位符的大小和路径

您可以使用模板的占位符名称来拥有自定义的图像加载器 .

```
opts.getImage = function (tagValue, tagName) {
    if(tagName === 'logo')
        return fs.readFileSync(__dirname + '/logos/' + tagValue);

    return fs.readFileSync(__dirname + '/images/' + tagValue);
};
```

同样的东西可以用来定制图像大小.

```
opts.getSize = function (img, tagValue, tagName) {
    if(tagName === 'logo')
        return [100, 100];

    return [300, 300];
};
```

## 基础64包括

您可以使用以下代码的 Base64 图像 :

```js
function base64DataURLToArrayBuffer(dataURL) {
  const base64Regex = /^data:image\/(png|jpg|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;
}
const imageOpts = {
  getImage(tag) {
    return base64DataURLToArrayBuffer(tag);
  },
  getSize() {
    return [100, 100];
  },
};
doc.attachModule(new ImageModule(imageOpts));
```

## 常见问题

### @chax-at/docxtemplater-image-module-free 是什么？

Docxtempter 的开源图像模块

### 如何安装 @chax-at/docxtemplater-image-module-free？

在项目目录运行 npm install @chax-at/docxtemplater-image-module-free，或使用 pnpm add / yarn add / bun add。

### @chax-at/docxtemplater-image-module-free 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/chax-at\_\_docxtemplater-image-module-free 是否存在。

### @chax-at/docxtemplater-image-module-free 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @chax-at/docxtemplater-image-module-free 可以商用吗？

@chax-at/docxtemplater-image-module-free 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @chax-at/docxtemplater-image-module-free 的下载量有多少？

根据 npm 官方下载统计，@chax-at/docxtemplater-image-module-free 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,545 次，日均约 85 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @chax-at/docxtemplater-image-module-free 还在维护吗？

最新版本 2\.0\.0 发布于 2026/06/30（4 个月前）；至今共发布 1 个版本，其中过去 12 个月发布了 1 个；首次发布于 2026/06/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

