使用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
相关产品推荐
相关产品推荐

