PPTX

补丁

通过替换占位符修改现有 .pptx 文件

通过替换 {{占位符}} 标记来修补现有 .pptx 模板,支持替换为新的文本块。

patchPresentation

替换现有 .pptx 文件中的占位符:

import { patchPresentation, PatchType, TextRun, Presentation, Packer } from "@office-open/pptx";
import { writeFileSync } from "node:fs";

// 创建带占位符的模板
const templatePres = new Presentation({
  title: "补丁演示",
  slides: [
    {
      children: [
        {
          shape: {
            x: 80,
            y: 120,
            width: 720,
            height: 80,
            textBody: {
              children: [{ children: [{ text: "你好 {{name}}!" }] }],
            },
          },
        },
      ],
    },
  ],
});

const templateBuffer = await Packer.toBuffer(templatePres);

// 修补模板
const result = await patchPresentation({
  outputType: "nodebuffer",
  data: templateBuffer,
  patches: {
    name: {
      type: PatchType.PARAGRAPH,
      children: [new TextRun({ text: "世界", bold: true, fontSize: 24 })],
    },
  },
});

writeFileSync("output.pptx", result);

PatchType

类型说明
PatchType.PARAGRAPH用内联运行级内容替换占位符

补丁将段落中的占位符文本替换为新的文本块。默认保留原 run 的格式属性(字体、大小、颜色、加粗等)。

patches: {
  title: {
    type: PatchType.PARAGRAPH,
    children: [
      new TextRun({ text: "你好 ", bold: true }),
      new TextRun("世界"),
    ],
  },
}

自定义分隔符

默认分隔符为 {{}}。使用 placeholderDelimiters 自定义:

await patchPresentation({
  outputType: "nodebuffer",
  data: templateBuffer,
  patches: { name: { type: PatchType.PARAGRAPH, children: [new TextRun("John")] } },
  placeholderDelimiters: { start: "<<", end: ">>" },
});

选项

选项类型默认值说明
outputTypestring输出格式(见导出页面)
dataBuffer | Uint8Array | ...输入 .pptx 文件数据
patchesRecord<string, IPatch>占位符名称到补丁内容的映射
keepOriginalStylesbooleantrue保留原始 run 格式属性
placeholderDelimiters{ start: string, end: string}{ {{, }} }自定义占位符分隔符

提示

  • PowerPoint 中跨分割运行的占位符会被库自动处理。
  • keepOriginalStyles 默认为 true,保留模板的 run 格式(字体、大小、颜色等)。
  • 所有幻灯片都会被处理 — 多张幻灯片上的相同占位符都会被替换。
  • 通过在补丁中包含 data(Uint8Array)可以替换 ppt/media/ 中的图片媒体文件。
Copyright © 2026