@s8fy/pptx-core
v3.17.0
Published
Framework-free PowerPoint (PPTX) model, parsing adapters, font lifecycle and PDF export helpers
Maintainers
Readme
@s8fy/pptx-core
Package guide · Viewer documentation · Commercial licensing · Report an issue
Framework-free PPTX parsing, shared slide types, font lifecycle helpers, Blob URL cleanup, and PDF export facade used by the viewer SDK packages.
Key Features
- A typed presentation model for custom viewers. Normalize parser output into pixel-based slide geometry, text runs, shapes, images, tables, charts, equations, and supported effects without depending on a UI framework or mounting the default viewer.
- Detailed chart semantics survive adaptation. Preserve series/point styles, missing-value slots, axes and labels, selected combination-chart groups, modern ChartEx data, and 3D scene metadata such as camera settings and chart walls. A custom renderer can consume these facts without reparsing OOXML.
- SmartArt, effects, and animation identities. Carry cached or supported native SmartArt shapes, text-fitting frames, drawing identities, chart/SmartArt animation subtargets, glyph effects, and shape/text 3D metadata into the shared model.
- Font preparation with explicit ownership. Browser font helpers deobfuscate supported ODTTF fonts, extract TrueType data from supported uncompressed EOT containers, and handle family/weight variants. MTX-compressed EOT is not decoded, and browser font loading can fail. PDF font resolution can use configured bytes, a self-hosted cache, optional user-approved local TrueType fonts, or remote fallback. Remote resolution can be disabled.
- CJK fallback coverage you can inspect. PDF resolution reports distinguish complete, partial, missing, and unknown coverage and list the affected codepoints. Coverage evidence helps an application decide whether to export or request another font; it is not a guarantee of shaping or final visual fidelity.
- Authored slide identity and navigation facts. Preserve slide part identities, hidden-slide flags, and internal link actions, including Last Slide Viewed. Keep every slide in the model while allowing consumers to distinguish sequential navigation from an explicit target.
- PDF conversion and resource lifecycle helpers. Convert original PPTX bytes through the shared WASM engine, resolve fonts separately from preview CSS, and release owned media URLs and injected fonts when their consumers finish.
Core owns model adaptation and shared helpers, not DOM painting or animation playback. Retained metadata describes what a renderer can consume; it does not certify that every Office feature is rendered. Most applications should use the Viewer facade. PDF export is static, requires original PPTX bytes and WebAssembly GC, and follows runtime authorization/watermark policy.
When to use this package
Use @s8fy/pptx-core when building a custom PPTX workflow around the normalized PptxPresentation model, shared font preparation, or resource/PDF helpers. Core does not mount a viewer or paint slides.
For browser previews, start with Viewer; for low-level parser output, use Parser. For standalone PDF/Markdown conversion, use Converter, whose API and product license are separate.
Install
pnpm add @s8fy/pptx-coreUse this package when you need the normalized PptxPresentation model without the built-in viewer UI. Most applications should install the higher-level @s8fy/pptx-viewer facade instead.
Parse a presentation
import { parsePptx, revokeBlobUrls } from '@s8fy/pptx-core'
const response = await fetch('/slides.pptx')
if (!response.ok) throw new Error(`PPTX request failed: ${response.status}`)
const deck = await parsePptx(await response.arrayBuffer())
try {
console.log(deck.width, deck.height, deck.slides.length)
// Consume the model here; keep it alive while its media is displayed.
} finally {
revokeBlobUrls(deck)
}parsePptx(buffer, options?) returns Promise<PptxPresentation>. Input must be an ArrayBuffer, not a URL or File; use await file.arrayBuffer() for browser files. The normalized model has width, height, slides, themeColors, optional fonts, and optional referencedFonts. Dimensions are in pixels. This is different from the low-level parser's ParseResult, whose dimensions live under size.
| Parse option | Default | Meaning |
| -------------- | ---------------- | ----------------------------------------------------------------------- |
| parser | 'wasm' | 'wasm' or 'js'; the low-level parser package instead defaults to JS |
| unzipMode | 'wasm' | ZIP engine for WASM parsing |
| extractFonts | false | Extract embedded font data; parsing does not install browser fonts |
| wasmUrl | Package-relative | Optional parser WASM URL, not the PDF engine URL |
| signal | None | AbortSignal for cancelling this request |
revokeBlobUrls(deck) releases media URLs owned by the returned model. Call it on the original model object after its last consumer finishes; cloning or serializing the model does not transfer cleanup ownership. Blob URLs are not portable persistent data.
Model and effect metadata
The normalized model preserves authored shape frames, chart fonts and styling, audio posters, SmartArt identities/fitting metadata, and supported chart/SmartArt animation subtargets. Cached SmartArt drawings take precedence; native projection covers selected uncached linear-process and organization-hierarchy profiles, not every layout.
Slide.sourcePart optionally preserves the package-root OPC part identity, and Slide.hidden optionally marks an authored hidden slide. Omitted hidden metadata means visible. The model retains every slide in presentation order; these fields do not renumber pages or remove hidden slides from static export. Synthetic and previously saved models may omit the new fields. Preserve part identities when rearranging parsed slides so authored internal links still resolve to the intended page.
TextEffects and Reflection are exported types. Text runs can carry textEffects (glyph glow/reflection) and textOutline; shape/text elements can carry innerShadow, reflection, shape3d, or text3d where applicable. Effects remain separate from glyph fill and outline. Presence in the model does not guarantee complete painting by a custom renderer; the shared renderer and PDF engine have their own support limits. Chart values can contain null for missing observations, so preserve point indexes and check values before computing with them.
Optional model fields also preserve picture-content imageOpacity independently of outlines, textHorizontalOverflow independently of vertical clipping, and explicit SmartArt textRect frames. Histogram binning accepts binCount, surface axes retain logBase, and ChartLegendItem.pointIndex identifies scatter point legends. Existing models can omit these fields.
Parsing refreshes supported short-date fields (datetime1, datetime, and date) from one host-local calendar snapshot per operation using the field language. Fixed date text and unsupported field types retain their cached text. PDF conversion uses the same display-date rules; this date does not alter license evaluation time.
Export PDF
import { pptxToPdf, downloadPdf } from '@s8fy/pptx-core'
export async function downloadPresentation(file: File): Promise<void> {
const bytes = await pptxToPdf(await file.arrayBuffer(), {
unicodeFallbackFont: { url: '/fonts/NotoSansSC-Regular.ttf' },
})
downloadPdf(bytes, file.name)
}Provide the example font at that URL, or omit the fallback for documents that do not need it. PDF conversion needs the original PPTX bytes, not just a PptxPresentation. pptxToPdf returns Promise<Uint8Array>; downloadPdf(bytes, fileName) only initiates a browser download and changes the extension to .pdf.
PptxToPdfOptions accepts signal, PDF wasmUrl, PDF workerUrl, license, watermark, regularFonts, unicodeFallbackFont, emojiFallbackFont, emojiBitmapFallback, mathFallbackFont, and officeFontFallbacks. Parser and PDF wasmUrl settings refer to different binaries. Unlike the low-level parser PDF API, this facade does not expose wasmBytes; unlike the viewer controller, it does not accept fontResolver directly.
For model-aware font resolution, call await resolvePdfFonts({ presentation: deck, resolver: { cacheBaseUrl: '/fonts/', remoteFonts: false } }). It returns { fonts, cjkFallback }: inspect the report, then spread fonts into pptxToPdf options. Browser preview fonts and PDF font bytes are separate; an installed CSS font alone does not supply PDF glyph data.
To add user-approved browser system fonts, set systemFonts: true in that resolver. It uses the Local Font Access API, which requires a supporting desktop browser, a secure context, and permission. TrueType sfnt bytes with either 0x00010000 or Apple's true signature are accepted without rewriting; CFF/OpenType (OTTO) fonts are skipped. Prepared cache fonts are tried before local fonts, and Google Fonts is a later source when enabled. remoteFonts: false disables automatic Google requests while retaining cache and explicitly configured direct URLs. Supply a self-hosted fallback for unsupported browsers, denied permission, or missing/unsupported local fonts; system-font access alone does not guarantee CJK coverage or an exact match to the original typeface.
CJK resolution reports since 3.2
resolvePdfFonts(input: PdfFontResolutionInput): Promise<PdfFontResolutionResult> replaces the option-only createPdfFontOptions API from 3.1.0. There is no compatibility alias. This API has been available since 3.2.0; 3.1.0 does not expose it.
Version 3.2 intentionally included incompatible API changes in a minor version while the SDK had no external consumers. Replace PdfFontOptionsInput with PdfFontResolutionInput, remove the unused embeddedFonts input, and pass result.fonts to conversion instead of the whole resolution result. Presentation font metadata remains available on the model.
import { resolvePdfFonts, type PptxPresentation } from '@s8fy/pptx-core'
export async function requireCjkFallback(deck: PptxPresentation) {
const result = await resolvePdfFonts({
presentation: deck,
resolver: { cacheBaseUrl: '/fonts/', remoteFonts: false },
})
if (!['complete', 'not-needed'].includes(result.cjkFallback.status)) {
throw new Error(`CJK fallback: ${result.cjkFallback.status}`)
}
return result.fonts
}Serve prepared fonts at that cache URL. cjkFallback.status is not-checked without a model, not-needed without visible CJK characters, missing with no coverage, partial with incomplete coverage, complete when every required codepoint has coverage evidence, or unknown when remaining coverage cannot be determined. The report includes requiredCodepoints, coveredCodepoints, missingCodepoints, unknownCodepoints, and coverageSources.
Coverage sources distinguish inspected Unicode cmap 4/12 mappings from declared css-unicode-range coverage of successfully downloaded Google faces. WOFF2/TTC without inspectable coverage, and explicit fallback URLs without loaded bytes, remain unknown; the report does not fetch those explicit URLs. Missing and unknown lists are disjoint. All visible CJK codepoints are checked, including those beyond Google's text-subset sample limit.
This report only describes returned CJK fallback assets. It does not include original-family fonts, embedded fonts, Latin/symbol fallbacks or emoji, and cannot certify shaping, font validity, style fidelity or the final PDF. A missing fallback does not prove an embedded-font PDF will fail. CSS coverage is a declaration, not decoded glyph verification. The resolver tolerates source failures; applications choose whether to reject partial/unknown, provide another source or use independently verified embedded/original fonts. Cache only results accepted by that policy; rejected results must be retryable. The Viewer does not automatically enforce the report.
For browser system fonts, prepare the model and import modules before export, and initiate Local Font Access directly from the user's click before asynchronous work can consume user activation. Keep successful results scoped to the same document, and discard stale results after replacement or disposal.
Browser font lifecycle
Custom renderers can use injectEmbeddedFonts(deck.fonts ?? []) and loadReferencedFonts(deck.referencedFonts ?? [], deck.fonts?.map(font => font.typeface), options). Both return cleanup functions; the latter also exposes a ready Promise and a pending flag. Release both when the view is disposed. The viewer controller handles this lifecycle automatically.
Referenced-font loading enables Google Fonts fallback by default. For self-hosted assets, use families or cacheBaseUrl with remoteFonts: false; explicit configured assets can still be fetched. See the exported BrowserFontResolverOptions and PdfFontSources types for the separate preview and PDF configurations.
Calibri can use Carlito and Arial can use Arimo when exact fonts are unavailable. These are compatible fallbacks, not guarantees of identical metrics or appearance. Browser font readiness can trigger later text fitting/painting; a parsed model alone does not wait for browser fonts.
Animation model since 3.2
As in 3.1, AnimationDegraded is a discriminated union with required kind. Version 3.2 removed its effect-fallback variant and AnimationEffect.previewFallback. Add kind: 'text-granularity' to application-created text diagnostics, and narrow before reading their fields:
import type { AnimationDegraded } from '@s8fy/pptx-core'
export function describeDegradation(diagnostic: AnimationDegraded): string {
switch (diagnostic.kind) {
case 'text-granularity':
return `${diagnostic.fromGranularity} -> ${diagnostic.toGranularity}`
case 'timing-fill':
return `${diagnostic.fromFill} -> ${diagnostic.toFill}`
}
}Timing-fill diagnostics use fromFill: 'transition' / toFill: 'hold' and no longer carry placeholder text-granularity fields. Interface extension and declaration merging against the former interface must be replaced with application-owned types. Reparse original PPTX bytes when upgrading persisted animation models; untagged raw degradation entries are no longer retained by normalization.
Supported dissolve entrance/exit element effects retain effect.kind: 'dissolve' and use deterministic scattered-cell masking in the Renderer. The shared model has no previewFallback flag or dissolve-to-fade diagnostic. Invalid source filter/phase combinations remain unplayable. Particle timing is a bounded visual approximation, not a claim of PowerPoint frame parity.
Drawing-group animation targets retain the exact slide-local leaf IDs in target.group; the leaves keep their own drawing identities. Checkerboard and blinds retain their effect family and horizontal/vertical axis. A paired visibility helper shares the concrete effect's click instead of becoming a second build. Missing group members never fall back to a layout/master shape with the same local ID.
Upgrading to 3.0
measureSingleLineTextWidthWithPretext and isPlayableAnimationStep are no longer exported from the package root. Remove those root imports and use the public model/parsing APIs or the renderer's controller for supported playback. @s8fy/pptx-core/internal exists for SDK sibling integration and is not a stable application API.
Authorization and errors
Core parsing normalizes data; it does not itself authorize display. Applications implementing a custom display should resolve authorization with resolveViewerPresentationAuthorization and apply its result, or use the viewer controller, which handles this automatically. PDF conversion resolves the bundled policy before conversion. Pass an issued license through license: { signedLicense }; missing or invalid licenses are evaluated under the applicable output rules, never assumed licensed.
Useful exported errors include AuthorizationDeniedError (reason), PptxFileSizeLimitError (code, sizeBytes, limitBytes), and ResourcePolicyError (details.reason, details.stage). Resource limits are independent of commercial entitlement. Catch rejected promises in parsing/export handlers.
Runtime and package entrypoints
Node.js 22.12+ is declared in the package. ESM and CommonJS entrypoints include their corresponding TypeScript declarations. Parsing and PDF conversion can run in Node; DOM rendering, browser font injection, and download helpers require a browser. WASM parsing/export requires WebAssembly GC support.
Bundled WASM assets use package-relative URLs by default. Keep deployed WASM/Worker files accessible, and serve WASM bytes rather than an HTML fallback page. Browser PDF export requires a working Web Worker. No framework dependency or viewer stylesheet is required just to parse or export.
License
This package is licensed under the Structurify Commercial & Evaluation License (see LICENSE). Free for local development, testing, POC evaluation, and noncommercial use; commercial production use requires a commercial license.
