You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用docx库添加图片时遇Type 'Blob'类型不兼容错误求助

解决docx库中ImageRun的Blob类型不兼容问题

问题原因

docx库的ImageRun构造函数的data参数不接受Blob类型,它只支持string | Buffer | Uint8Array | ArrayBuffer这几种类型,直接传入fetch返回的Blob对象会触发TypeScript类型检查错误。

解决方案

将Blob转换为ArrayBuffer(或Uint8Array)即可,利用Blob的arrayBuffer()方法完成转换。

修改后的完整代码

const runWord = async () => {
  // 直接获取ArrayBuffer,跳过Blob转换步骤
  const testImg = await fetch("https://raw.githubusercontent.com/dolanmiu/docx/master/demo/images/cat.jpg")
                        .then((r) => r.arrayBuffer());
  const doc = new docs.Document({
    sections: [
      {
        properties: {},
        children: [
          new docs.Paragraph({
            children: [
              new docs.TextRun("Hello World"),
              new docs.TextRun({
                text: "Foo Bar",
                bold: true
              })
            ]
          }),
          new docs.Paragraph({
            children: [
              new docs.ImageRun({
                data: testImg, // 现在是ArrayBuffer类型,符合参数要求
                transformation: {
                  width: 100,
                  height: 100
                }
              })
            ]
          })
        ]
      }
    ]
  });
  docs.Packer.toBlob(doc).then((blob) => {
    saveAs(blob, "Test Document.docx");
  });
};

另一种转换方式(若需先保留Blob)

如果业务需要先处理Blob对象,再转换为支持的类型:

const runWord = async () => {
  const blob = await fetch("https://raw.githubusercontent.com/dolanmiu/docx/master/demo/images/cat.jpg")
                      .then((r) => r.blob());
  // 将Blob转为ArrayBuffer
  const testImg = await blob.arrayBuffer();
  
  // 后续文档构造代码与上述一致
  const doc = new docs.Document({ /* ... */ });
  docs.Packer.toBlob(doc).then((blob) => {
    saveAs(blob, "Test Document.docx");
  });
};

内容的提问来源于stack exchange,提问作者PRATIK CHHETRI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:35:03