@nextgensoftwares/folio-pptx
PowerPoint import and export for @nextgensoftwares/folio-slides. DOM-free. Depends on @nextgensoftwares/folio-slides, @nextgensoftwares/folio-import/xml and fflate. Guide: Slides & PPTX.
Import
importPptx(bytes, PptxImportOptions?) → PptxImportResult
| Option | Meaning |
|---|---|
media?: 'ref' | 'data-url' | pictures as media: references (default; resolve with mediaBytes) or inline data: URLs |
limits?: Partial<PptxLimits> | maxBytes (1 GB), maxEntries (50,000), maxDepth (256), maxSlides (5,000); over a limit throws PptxLimitError |
onWarning?(warnings) | called once with every warning |
Also read: sections (presentation.sections), the notes page layout (presentation.notesPage: p:notesSz and the notes master's placeholders) and what notes pages show (presentation.notesHeaderFooter: the notes master's header, date, footer and page number placeholders and its p:hf). Export patches the notes master when that changes (text into the placeholders, added in PowerPoint's corners when missing; p:hf listing the parts turned off), or writes a notes master for a deck that needs one; every value written is escaped. The handout master reads the same way (presentation.handoutPage: its placeholders' boxes and what they show, plus its background, its other shapes, its theme and colour map, and the placeholders themselves in metaShapes for their text styling) and is patched the same way when that changes; a deck without one gets none.
PptxImportResult: { presentation, package: PptxPackage, warnings: ImportWarning[], embeddedFonts } (embeddedFonts: decoded .fntdata faces, EmbeddedFontFace & { subset }).
openPptx(bytes, OpenPptxOptions?) → Promise<OpenPptxResult>: importPptx plus the shared font policy (fonts: ImportFontsOptions, see import); OpenPptxResult.fonts: DocumentFont[]. convertImage?: ImageConverter ((asset: ImportAsset) => Promise<ImportAsset | null | undefined>, as in folio-docx) converts pictures browsers can't draw (EMF, WMF, TIFF) for display, e.g. through LibreOffice on a server: results become the package's previews, which mediaBytes returns, while export writes the original part; image-format warnings of types that all converted are dropped. WMF/EMF pictures it doesn't convert get an SVG preview from folio-metafile. Keep package beside the presentation: export patches it.
Big decks: from a File, in a worker
openPptxFile(file: Blob, OpenPptxOptions?) → Promise<OpenPptxResult> opens a deck without holding the file: XML, relationships and small parts are read in (a few merged reads of the archive), big media (pictures, audio, video over 64 KB) stay in the file as Blobs on the package (package.blobs; stored parts are slices of the file, nothing read; deflated ones are inflated one at a time into Blobs of their own). mediaBlob(pkg, src) returns what a media: src draws from as a Blob, for URL.createObjectURL (createMediaResolver in plugin-slides takes it). Archives this reader doesn't handle (ZIP64, encrypted) are read whole.
openPptxInWorker(file, worker, OpenPptxOptions?) does the same off the main thread, so opening never freezes the page; the font policy and convertImage then run on the main thread (measureText stays behind: SmartArt saved without a drawing gets estimated widths). The worker is this package's ./worker entry, started by the host:
// open-worker.ts (bundled as a module worker)
import '@nextgensoftwares/folio-pptx/worker';
// app
const worker = new Worker(new URL('./open-worker.ts', import.meta.url), { type: 'module' });
const { presentation, package: source } = await openPptxInWorker(file, worker);
const media = createMediaResolver((src) => mediaBlob(source, src));On a 1000-slide, 395 MB deck in Chrome, the page's JavaScript heap after opening is 54 MB (475 MB holding the file's bytes), and the longest main-thread stall 0.3 s (1 s).
A package opened this way exports with exportPptxFile(deck, { package }) → Promise<Uint8Array>, which reads the media back in for the copy it writes; exportPptx refuses it (it would leave them out). answerOpen(request) (the ./worker entry) answers one request for custom transports.
Connectors (p:cxnSp) keep the shapes they are glued to (a:stCxn / a:endCxn → SpShape.cxn), written back with the connector's locks in p:cNvCxnSpPr.
Text anchoring follows DrawingML: a body with no anchor is top-anchored unless the theme's a:objectDefaults (spDef for shapes, txDef for text boxes, read into SlideTheme.objectDefaults) or the placeholder chain says otherwise; an explicit anchor always wins. Shapes inserted by the editor are written with anchor="ctr" and centred paragraphs (PowerPoint's defaults); text boxes with wrap="square", spAutoFit and top-left text.
looksLikePptx(bytes) sniffs a ZIP with presentation parts; isZip(bytes).
Export
exportPptx(pres, PptxExportOptions?) → Uint8Array. With { package } it patches the source: untouched parts and slides byte for byte, edited slides shape by shape, new/deleted/reordered slides through relationships, content types and sldIdLst. Slide masters the package doesn't have (slides reused with their own formatting, reuseSlides) are written as new parts, with their layouts, their theme when it is new too, and a sldMasterIdLst entry. Without a package it writes a complete new one. A picture's fit (cover / contain) is written as the a:srcRect crop that shows the same (PowerPoint's Crop ▸ Fill / Fit), from the image's size in the package or added with it; web pictures need { imageSize: (src) => ({ width, height }) }, else they are written stretched.
{ measurer } (the one the editor lays out with) writes the shrink Folio draws for text edited in a shrink-to-fit (normAutofit) box as its fontScale (bakeAutofit in folio-slides); PowerPoint only recomputes autofit when the text is edited there. Untouched imported shapes keep the stored scale.
Drawing guides (Presentation.guides) are read from presentation.xml's p15:sldGuideLst extension (PowerPoint 2013+, with colours), else from viewProps.xml's slide-view p:guideLst, and written to both only when they changed (positions in 1/8 pt, 6 per px).
Also written back: speaker notes (an edited notes page is rewritten, new notes get a notes page and, the first time, a notes master with a theme of its own), sections (Presentation.sections, PowerPoint's p14:sectionLst: read with their slides, rewritten when they or the slide list change, removed when the deck has none; a deck that never had them keeps the file's, fitted to the new slide list), header and footer placeholders on slides (date fields datetime1…datetime13, slidenum, footer text), transitions (base-schema effects; others as a fade), theme colours and fonts, and docProps/app.xml counts. Outer shadows on pictures (p:spPr/a:effectLst/a:outerShdw) and tables (a:tblPr/a:effectLst) read into PicShape.shadow / TableShape.shadow and are written back there. A duplicated slide's charts, SmartArt and OLE frames are copied with parts of their own. Equations: PowerPoint's (a14:m, read from the mc:AlternateContent choice instead of its picture fallback) import as math runs (TextRun { kind: 'math', latex, display? }), and embedded MathType / Equation Editor 3 objects as GraphicShape.math (LaTeX; drawn as math, the frame kept on export). A shape with equations is written in mc:AlternateContent: Office Math for PowerPoint, plain text for older readers; equations that didn't change keep their original markup, edited ones are written from LaTeX (latexToOmml, folio-import/math). Values PowerPoint range-checks (font sizes, extents, line widths, angles, margins, spacing) are clamped; a web picture (https://…) is linked, and only PNG, JPEG, GIF and BMP data URLs are embedded (convert others first). Audio and video (PicShape.media + mediaSrc) are read from and written as PowerPoint's media pictures: embedded parts (a:videoFile/a:audioFile with the p14:media extension) or linked URLs. Embedded web pages (PicShape.embed) are written as their poster picture linking to the page (PowerPoint follows the link) plus a Folio extension that brings the embed back. Slide comments (Slide.comments) are read from and written to PowerPoint's comments parts with their authors; replies are written as PowerPoint threaded comments (p15:threadingInfo naming the parent) and read back into the thread, and a resolved thread carries a Folio extension (legacy comments have no resolved state).
Package
PptxPackage: parts (name → bytes, names as stored: a Map whose parts are inflated when read, so opening a deck reads only the archive's directory; stored media are views of the file, the most recently inflated parts are cached up to 32 MB), blobs (media left in the file, opened with openPptxFile), has(part), blob(part), withMedia() (a copy with them read in), name(part), bytes(part), xml(part) (parsed parts cached, the 64 most recently read), rels(part) → Map<string, Relationship>, relOfType(part, type), contentType(part), limits. relsPath(part). Relationship: { id, type, target, external }. DEFAULT_LIMITS, PptxLimits, PptxLimitError.
mediaBytes(pkg, src) → { data, type } for a media: src (null for media left in the file: mediaBlob(pkg, src) → Blob); mimeOf(path).
Validation
validatePptx(bytes) → string[]: the structural checks PowerPoint enforces (content types, relationships, ids, child order of the sequences it validates, mc:Ignorable prefixes, duplicate and required attributes, sections) and semantic ones: every r: reference resolves, ranged values stay in range, pictures have an image, notes pages link their slide and the notes master, master and layout ids are unique and listed both ways, chart and diagram parts belong to one slide. Dev only: tools/ooxml-validate (ECMA-376 transitional XSDs via lxml) and tools/ooxml-sdk/validate.sh (the Open XML SDK in a private .NET 8, no sudo; the slides fidelity run uses it when installed).
Diagnostics
ImportWarning { code, severity, message, part?, slide?, shape?, detail?, count }; WarningCode: geometry-approx, geometry-unsupported, geometry-formula, fill-approx, effect-dropped, chart-preview, diagram-preview, ole-preview, graphic-unknown, media-poster, image-format, missing-part, external-link, font-missing, font-substituted, font-embed-restricted, text-vertical, text-columns, text-warp, text-nowrap, animation-kept, transition-approx, font-embedded, strict-ooxml, xml-malformed, limit.
Diagnostics (collector merging repeats; add(WarningInput), list), summarizeWarnings(list) → counts by code (safe for telemetry: warnings never hold document text).
Charts are read with their data (GraphicShape.chart). When the data was edited, export rewrites the chart part: series names, categories and values become literals, series are added or removed, and the link to the embedded workbook (which holds the old data) is dropped. Type, styles and axes are kept. Copies get their own patched part. SmartArt keeps its four parts on the frame (GraphicShape.diagram). After an edit, export writes the data part, with presentation points regenerated, and the drawing part, so LibreOffice and older readers show the change; copies get their own parts. A diagram inserted in Folio gets all five parts (data, layout, quick style, colours, drawing) with their relationships and content types. Masters and layouts edited in master view are patched like slides (shape tree, background, a master's colour map).