PPTX

图片

嵌入图片、设置幻灯片背景以及在形状上使用图片填充

@office-open/pptx 支持将图片嵌入幻灯片、设置背景图片以及将图片用作形状填充。

嵌入图片

import { Slide, Picture } from "@office-open/pptx";
import fs from "node:fs";

new Slide({
    children: [
        new Picture({
            x: 1,
            y: 1,
            width: 4,
            height: 3,
            data: fs.readFileSync("photo.png"),
            imageType: "png",
        }),
    ],
});

从 URL 加载图片(浏览器)

const response = await fetch("https://example.com/image.png");
const arrayBuffer = await response.arrayBuffer();
const data = new Uint8Array(arrayBuffer);

new Picture({
    x: 1,
    y: 1,
    width: 5,
    height: 3,
    data,
    imageType: "png",
});

支持的图片类型

类型扩展名imageType
JPEG.jpg / .jpeg"jpg"
PNG.png"png"
GIF.gif"gif"
BMP.bmp"bmp"
SVG.svg"svg"
TIFF.tiff"tiff"

幻灯片背景图片

为整张幻灯片设置背景图片:

import { Slide } from "@office-open/pptx";
import fs from "node:fs";

new Slide({
    background: {
        type: "image",
        data: fs.readFileSync("background.png"),
        imageType: "png",
    },
    children: [
        // 幻灯片内容显示在背景之上
    ],
});

纯色背景

new Slide({
    background: { type: "solid", color: "1F4E79" },
    children: [],
});

渐变背景

new Slide({
    background: {
        type: "gradient",
        stops: [
            { position: 0, color: "0D47A1" },
            { position: 100, color: "42A5F5" },
        ],
        angle: 45,
    },
    children: [],
});

形状上的图片填充(Blip Fill)

将图片用作任何形状的填充:

import { Shape } from "@office-open/pptx";
import fs from "node:fs";

new Shape({
    x: 1,
    y: 1,
    width: 6,
    height: 4,
    geometry: "roundRect",
    fill: {
        type: "blip",
        data: fs.readFileSync("texture.png"),
        imageType: "png",
    },
    text: "Text over image fill",
    paragraphs: [
        new Paragraph({
            children: [
                new TextRun({
                    text: "Shape with image fill",
                    fontSize: 24,
                    bold: true,
                    color: "FFFFFF",
                }),
            ],
        }),
    ],
});

尺寸和定位

所有位置和尺寸值均以英寸为单位:

new Picture({
    x: 1, // 左边距位置(英寸)
    y: 0.5, // 顶部位置(英寸)
    width: 8, // 宽度(英寸)
    height: 4.5, // 高度(英寸)
    data: imageData,
    imageType: "png",
});

需要像素到 EMU 的转换时,使用 convertPixelsToEmu

import { convertPixelsToEmu } from "@office-open/pptx";

const emu = convertPixelsToEmu(800); // 将 800 像素转换为 EMU
Copyright © 2026