Skip to content

Loading & Parsing ​

Loading turns raw .pptx, legacy .ppt, or pptx-viewer-json bytes into a fully resolved, typed PptxData object. All parsing happens in memory - no temporary files, no native code.

Construct a handler and load ​

ts
import { PptxHandler } from 'pptx-viewer-core';

const handler = new PptxHandler();
const data = await handler.load(arrayBuffer);

console.log(`${data.slides.length} slides loaded`);
console.log(`Canvas: ${data.width} x ${data.height}`);

handler.load(data, options?) accepts an ArrayBuffer and returns Promise<PptxData>. It recognizes OpenXML ZIP packages, legacy OLE2 PowerPoint files, and a JSON object carrying the "format": "pptx-viewer-json" marker.

Keep the handler

The handler holds the in-memory ZIP. Use the same handler instance to later save() or fetch media via getImageData() / getMediaArrayBuffer().

Getting an ArrayBuffer ​

The engine is environment-agnostic; you just need bytes.

ts
const buffer = await fetch('presentation.pptx').then((r) => r.arrayBuffer());
const data = await handler.load(buffer);
ts
const file = input.files[0]; // File from <input type="file">
const buffer = await file.arrayBuffer();
const data = await handler.load(buffer);
ts
import { readFile } from 'node:fs/promises';

const node = await readFile('presentation.pptx'); // Buffer
const buffer = node.buffer.slice(node.byteOffset, node.byteOffset + node.byteLength);
const data = await handler.load(buffer as ArrayBuffer);

What the load pipeline does ​

When you call load(), the runtime:

  1. Detects the file format. Portable JSON is validated and overlaid on a generated blank archive. Encrypted OpenXML OLE2/CFB files are decrypted first when a password is supplied, and legacy binary PowerPoint files are converted to the model.
  2. Opens the ZIP with JSZip and parses [Content_Types].xml and ppt/presentation.xml.
  3. Parses each slide master, its theme, colour map, and layouts.
  4. For each slide, parses the shape tree and resolves the layout → master → theme style chain (see /guide/architecture).
  5. Parses text with style inheritance, animations, transitions, and media relationships.
  6. Parses comments, document properties, and embedded fonts.

The result is a single PptxData object holding everything needed to render, edit, or convert the deck.

Portable deck JSON ​

PptxJsonConverter produces a versioned, self-contained pptx-viewer-json document. It carries the presentation model and binary model fields as tagged base64, so it can be transferred without the original archive. load() recognizes its format marker automatically and prepares a minimal archive so ordinary editing and save() continue to work.

ts
import { PptxHandler, PptxJsonConverter } from 'pptx-viewer-core';

const json = PptxJsonConverter.toJson(data, { pretty: true, generator: 'my-app' });
const imported = new PptxHandler();
const restored = await imported.load(new TextEncoder().encode(json).buffer);
const bytes = await imported.save(restored.slides); // valid .pptx bytes

The current format is version 1. Use PptxJsonConverter.parse() when you need validation without rebuilding PptxData, or fromJson() when you only need the model.

Load options ​

ts
const data = await handler.load(buffer, {
	password: 'secret', // decrypt an encrypted file (see below)
	allowExternalImages: false, // default false - http(s) image URLs are dropped
	maxUncompressedBytes: 500 * 1024 * 1024, // zip-bomb guard, 500 MiB default
	limits: { maxSlides: 500, maxShapes: 50_000 }, // optional host limits, see below
});
OptionDefaultPurpose
password-Decrypts an encrypted package before parsing.
allowExternalImagesfalseWhen false, relationship targets resolving to http:///https:// are dropped from rendered slides (SSRF / privacy mitigation). Set true to allow them through.
limits-Host limits: maxInputBytes, maxUncompressedBytes (wins over the option above), maxEntries, maxSlides, maxShapes. See Load limits.
maxUncompressedBytes500 MiBTotal uncompressed budget. Exceeding it (or 65,536 entries) rejects with ZipBombError.
eagerDecodeImagesfalseDecode embedded images during load rather than lazily.
eagerDecodeEmbeddedFontsfalseDecode every embedded font variant during load, and omit the ones that fail, rather than on first use (see below).

Load limits ​

limits bounds one load for hosts that open untrusted decks. Each field left out keeps its default, so omitting limits changes nothing: 500 MiB inflated, 65,536 ZIP entries, and no limit on input size, slides or shapes. Each check runs before the work it bounds: maxInputBytes before the input is sniffed, decrypted or unzipped, maxEntries and maxUncompressedBytes before any part is inflated (and again while parts are read), maxSlides right after ppt/presentation.xml is parsed, and maxShapes as each slide's shapes are parsed (layout and master shapes are not counted).

A pptx-viewer-json document gets the same limits, whether it comes through load() or handler.loadFromJson(text, { limits }). For loadFromJson, maxInputBytes is the UTF-8 size of the text, checked before it is parsed. maxSlides and maxShapes are checked on the document's slides before any of it is used, with the same count as a .pptx package: every element, group members included at any depth, except the layout and master elements a loaded deck carries (ids starting layout- or master-). A deck loaded under a limit therefore loads under the same limit after a round trip through JSON.

maxInputBytes, maxSlides and maxShapes reject with PptxLoadLimitError (code PPTX_LOAD_LIMIT, with limit, maximum and actual). maxUncompressedBytes and maxEntries keep rejecting with ZipBombError (code ZIP_BOMB), which now also carries loadLimit and actual. getPptxLoadLimitViolation reads either:

ts
import { getPptxLoadLimitViolation, PptxHandler } from 'pptx-viewer-core';

try {
	await new PptxHandler().load(buffer, { limits: { maxSlides: 100 } });
} catch (error) {
	const violation = getPptxLoadLimitViolation(error);
	if (violation) {
		console.warn(`${violation.limit}: ${violation.actual} > ${violation.maximum}`);
	}
}

A value that is not a positive finite number, or a maxEntries above 65,536, throws RangeError before any work. When a slide or shape limit stops a load, the handler releases what it had parsed; it can still be disposed or load another deck.

Layout template images ​

await handler.getTemplateElementsForSlide(slideId) resolves embedded pictures and their SVG variants for the requested layout and master elements, including a previously unused layout after inserting a slide or applying that layout. Unused layouts are not all decoded during the initial load. Resolution uses the handler's media cache and updates the existing template objects without replacing their rawXml references. Missing assets remain unresolved, and the allowExternalImages policy is unchanged.

Embedded fonts ​

data.embeddedFonts lists one PptxEmbeddedFont per embedded family and style variant. By default load() reads each font part but does not decompress (EOT/MicroType Express) or de-obfuscate it: a variant's dataUrl, format and rawFontData are decoded the first time one of them is read, so existing synchronous code keeps working. Metadata (name, bold, italic, partPath, fontGuid, originalRId, originalPartBytes) never triggers decoding.

ts
const data = await handler.load(buffer);
const font = data.embeddedFonts?.find((f) => f.name === 'Lato' && !f.bold && !f.italic);
const decoded = font?.load ? await font.load() : font; // null when the part cannot be decoded
console.log(decoded?.dataUrl.slice(0, 32), font?.isLoaded);
  • load() decodes once and caches the result; concurrent calls share one promise. Decoding still runs on the calling thread.
  • load and isLoaded are not enumerable, so spreading, structuredClone and JSON.stringify see the same fields as before (reading them decodes the variant).
  • A descriptor owns its bytes and stays usable after the handler is disposed or loads another file.
  • Saving writes a variant that was never decoded back from its original part bytes, the same bytes an eager load would write. An edited rawFontData is re-embedded as before.
  • A variant whose part only fails when decompressed (a corrupt EOT payload) stays in the list with an empty dataUrl and no rawFontData. Pass eagerDecodeEmbeddedFonts: true to decode up front and drop such variants, as earlier versions did.

Accessing slides, theme, and metadata ​

ts
const data = await handler.load(buffer);

// Slides
const first = data.slides[0];
console.log(first.id, first.elements.length, first.notes);

// Canvas / dimensions
console.log(data.width, data.height); // pixels

// Theme
console.log(data.theme?.name);
console.log(data.theme?.fontScheme?.majorFont?.latin);

// Document metadata
console.log(data.coreProperties?.title, data.coreProperties?.creator);

// Structure
console.log(data.sections, data.slideMasters, data.slideLayouts);

See /guide/data-model for the full shape of PptxData, PptxSlide, and friends.

Iterating elements and narrowing by type ​

Every slide's elements array is a list of PptxElement - a discriminated union of 16 variants. Always narrow with the type discriminant before touching variant-specific fields:

ts
for (const slide of data.slides) {
	for (const el of slide.elements) {
		switch (el.type) {
			case 'shape':
			case 'text':
				console.log('text:', el.text);
				break;
			case 'image':
				console.log('image at', el.imagePath);
				break;
			case 'table':
				console.log('table rows:', el.tableData?.rows.length);
				break;
			case 'chart':
				console.log('chart type:', el.chartData?.type);
				break;
			case 'group':
				// groups nest child elements recursively
				console.log('group children:', el.children.length);
				break;
		}
	}
}

Narrow before access

TypeScript only exposes variant fields (like imagePath or tableData) after you've narrowed on el.type. This is the intended pattern - see /guide/data-model.

Embedded media ​

To pull bytes for an embedded image or media file referenced by an element:

ts
const dataUrl = await handler.getImageData(element.imagePath); // base64 data URL
const bytes = await handler.getMediaArrayBuffer(mediaPath); // ArrayBuffer

Encrypted files ​

If the file is password-protected and you call load() without a password, the engine throws EncryptedFileError. Provide options.password to decrypt before parsing:

ts
const data = await handler.load(buffer, { password: 'secret' });

See /core/encryption for the full encryption and write-back API.

Released under the Apache-2.0 License.