跳到主要内容

插入图片

场景说明

在文档中插入图片,支持嵌入式图片和浮动图片两种方式。

适用场景:

  • 文档图片插入
  • 图文混排
  • 图片水印
  • 报告生成

相关 API 文档

示例代码

插入嵌入式图片

<input type="file" id="imageInput" accept="image/*" />

<script>
async function insertInlineImage() {
const inputElement = document.getElementById('imageInput');

inputElement.onchange = async function() {
const file = inputElement.files[0];

// 获取插入位置(可以是当前选区或书签)
const bookmark = await Application.ActiveDocument.Bookmarks.item('imagePlaceholder');
const range = await bookmark.range;

// 插入嵌入式图片(随文字流动)
// 参数:file - 图片文件对象
// range - 插入位置(可选,默认当前选区)
// bReplace - 是否替换区域内容(可选,默认 false)
const inlineShape = await Application.ActiveDocument.InlineShapes.addPicture(
file,
range,
false // false: 不替换区域内容,在区域开始位置插入
);

console.log('嵌入式图片插入成功');
};
}
</script>

插入浮动图片

async function insertFloatingImage() {
const inputElement = document.getElementById('imageInput');

inputElement.onchange = async function() {
const file = inputElement.files[0];

// 获取插入位置
const bookmark = await Application.ActiveDocument.Bookmarks.item('floatImagePlace');
const range = await bookmark.range;

// 插入浮动图片(可自由定位,不随文字流动)
// 参数:file - 图片文件对象
// left - 左边距(可选,暂不支持)
// top - 上边距(可选,暂不支持)
// width - 宽度(可选,单位:磅)
// height - 高度(可选,单位:磅)
// range - 插入位置(可选)
// wrapType - 文字环绕类型(可选)
const shape = await Application.ActiveDocument.Shapes.addPicture(
file,
undefined, // left(暂不支持)
undefined, // top(暂不支持)
200, // width: 宽度 200 磅
150, // height: 高度 150 磅
range,
Word.WdWrapType.wdWrapFront // 文字环绕类型:浮于文字上方
);

// 其他环绕类型:
// Word.WdWrapType.wdWrapBehind - 衬于文字下方
// Word.WdWrapType.wdWrapInline - 嵌入到文字中

console.log('浮动图片插入成功');
};
}

注意事项

  • 图片文件大小限制为 10MB
  • 嵌入式图片:插入在文字层,随文字流动,适合文档内容图片
  • 浮动图片:插入在绘图层,可自由定位,适合水印、背景图等
  • bReplace 参数:true 会删除区域内容后插入图片,false 在区域开始位置插入
  • 浮动图片的 lefttop 参数暂不支持
  • 可以通过 Word.WdWrapType 枚举设置文字环绕方式