DOCX
图片
在文档中插入图片,支持缩放、旋转、裁剪和浮动定位
使用 ImageRun 在段落中嵌入图片。支持 JPG、PNG、GIF、BMP、SVG 等格式。
基本图片
import { Document, Packer, Paragraph, ImageRun } from "@office-open/docx";
import { readFileSync } from "node:fs";
const imageBuffer = readFileSync("photo.png");
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new ImageRun({
type: "png",
data: imageBuffer,
transformation: {
width: 200,
height: 150,
},
}),
],
}),
],
},
],
});
变换
控制尺寸、旋转和翻转:
new ImageRun({
type: "jpg",
data: imageBuffer,
transformation: {
width: 300,
height: 200,
rotation: 45, // 旋转 45 度
flip: {
horizontal: true, // 水平翻转
},
},
});
裁剪
使用 srcRect 裁剪源图片:
new ImageRun({
type: "png",
data: imageBuffer,
transformation: {
width: 200,
height: 200,
},
srcRect: {
left: 1000, // 裁剪左边缘(EMU 单位)
top: 1000, // 裁剪上边缘(EMU 单位)
right: 1000, // 裁剪右边缘(EMU 单位)
bottom: 1000, // 裁剪下边缘(EMU 单位)
},
});
浮动图片
使用 floating 选项进行带文字环绕的图片定位:
new ImageRun({
type: "png",
data: imageBuffer,
transformation: {
width: 150,
height: 150,
},
floating: {
horizontalPosition: {
offset: 720000, // 距页面左侧的位置(EMU 单位)
},
verticalPosition: {
offset: 720000, // 距页面顶部的位置(EMU 单位)
},
wrap: {
type: "square", // 文字环绕图片
},
},
});
图片效果(Blip Effects)
使用 blipEffects 直接对图片应用调整效果:
new ImageRun({
type: "jpg",
data: imageBuffer,
transformation: { width: 150, height: 150 },
blipEffects: {
// 亮度 +30%,对比度 -20%
luminance: { bright: 30, contrast: -20 },
},
});
可用的图片效果
| 属性 | 类型 | 说明 |
|---|---|---|
grayscale | boolean | 转为灰度图 |
luminance | { bright?, contrast? } | 调整亮度/对比度(百分比) |
hsl | { hue?, saturation?, luminance? } | 调整 HSL 颜色值 |
tint | { hue?, amount? } | 应用着色 |
duotone | { color1, color2 } | 双色调映射 |
biLevel | { threshold } | 黑白阈值(0-100) |
灰度
new ImageRun({
type: "jpg",
data: imageBuffer,
transformation: { width: 150, height: 150 },
blipEffects: { grayscale: true },
});
双色调
new ImageRun({
type: "jpg",
data: imageBuffer,
transformation: { width: 150, height: 150 },
blipEffects: {
duotone: {
color1: { value: "002060" },
color2: { value: "D0CECE" },
},
},
});
着色
new ImageRun({
type: "jpg",
data: imageBuffer,
transformation: { width: 150, height: 150 },
blipEffects: {
tint: { hue: 6000000, amount: 40 },
},
});
SVG 带回退
new ImageRun({
type: "svg",
data: svgBuffer,
transformation: { width: 200, height: 200 },
fallback: {
type: "png",
data: pngBuffer,
},
});