PPTX
@office-open/pptx
使用声明式 TypeScript API 生成、解析和修补 .pptx 演示文稿
安装
pnpm add @office-open/pptx
npm install @office-open/pptx
yarn add @office-open/pptx
bun add @office-open/pptx
快速开始
{
"slides": [
{
"children": [
{
"shape": {
"x": "1.3cm",
"y": "1.3cm",
"width": "20cm",
"height": "3cm",
"textBody": { "children": ["Hello World"] }
}
}
]
}
]
}
import { generatePresentation } from "@office-open/pptx";
const buffer = await generatePresentation({
slides: [
{
children: [
{
shape: {
x: "1.3cm",
y: "1.3cm",
width: "20cm",
height: "3cm",
textBody: { children: ["Hello World"] },
},
},
],
},
],
});
主要组件
| 组件 | 说明 |
|---|---|
slides | 演示文稿根选项,包含幻灯片和属性 |
slide | 单张幻灯片,包含形状、媒体和布局 |
shape | 矩形、圆角矩形和自定义几何形状 |
group | 分组形状,支持集体变换 |
| 段落和文本运行 | 形状内的文本段落和文本块 |
table | 表格,支持合并单元格和样式 |
picture | 幻灯片上的嵌入图片 |
chart | 柱状图、折线图、饼图、面积图和散点图 |
smartart | 预定义 SmartArt 图示 |
video, audio | 嵌入视频和音频 |
line, connector | 元素之间的线条和连接符 |
transition | 幻灯片切换效果 |
animation | 形状进入、强调和退出动画 |
background | 幻灯片背景 — 纯色、渐变和图片填充 |
headers / footers | 幻灯片页脚,支持日期、编号和文本 |
hyperlink | 形状和文本上的可点击超链接 |
| 幻灯片母版和版式 | 幻灯片母版和版式,统一设计风格 |
notes | 每张幻灯片的演讲者备注 |
theme | 配色方案和字体方案 |
modifyVerifier | 演示文稿修改密码保护 |
photoAlbum | 相册布局和框架设置 |
ole | 嵌入 OLE 对象 |
lockedCanvas | 锁定画布,包含不可编辑的绘图对象 |
导出格式
每个异步方法都有对应的同步版本(如 generatePresentationSync)。完整列表见页面。
| 方法 | 返回值 | 适用场景 |
|---|---|---|
generatePresentation(opts) | Buffer | Node.js 文件 I/O |
generatePresentation(opts, { type: "blob" }) | Blob | 浏览器下载 |
generatePresentation(opts, { type: "base64" }) | string | Data URL、API 载荷 |
generatePresentation(opts, { type: "string" }) | string | 调试、检查 |
generatePresentationStream(opts) | ReadableStream<Uint8Array> | 流式传输大文件 |
补丁
通过替换 {{占位符}} 标记修改现有 .pptx 模板:
import { patchPresentation } from "@office-open/pptx";
const result = await patchPresentation({
outputType: "nodebuffer",
data: templateBuffer,
placeholders: {
title: [{ text: "已更新", bold: true }],
},
});
详见。
解析
使用 parsePresentation 解析现有 .pptx 文件,返回 PresentationOptions:
import { parsePresentation } from "@office-open/pptx";
const opts = parsePresentation(buffer);
// opts.slides![0].children — 形状、表格、图表等
// opts.slides![0].background — 幻灯片背景
// opts.slides![0].transition — 切换效果
// opts.slides![0].notes — 演讲者备注
// opts.title, opts.creator — 核心属性
// opts.size — 幻灯片尺寸("16:9"、"4:3" 或自定义)
详见 。
幻灯片尺寸
使用 size 选项设置幻灯片尺寸。接受 "16:9"、"4:3" 或自定义 { width, height } 对象(单位为 EMU 或通用度量,如 "5cm"、"200px")。
import { generatePresentation } from "@office-open/pptx";
const buffer = await generatePresentation({
size: "16:9",
slides: [
// ...
],
});
| 尺寸 | 说明 |
|---|---|
"16:9" | 13.33" × 7.5"(宽屏) |
"4:3" | 10" × 7.5"(标准) |
{ width, height } | 自定义尺寸(EMU 或通用度量) |