Viewer Instance API
createPptxViewer returns a PptxViewerInstance, the imperative equivalent of the other bindings' template refs / handles. All toolbar operations are also available as instance methods, so you can hide the chrome (showToolbar: false, showThumbnails: false) and drive the viewer from your own UI. The interface extends the shared PowerPointViewerAPI implemented by every binding, so the getContent / goTo / getSlides-style methods below match the React, Vue, Angular, and Svelte handles.
import { createPptxViewer, type PptxViewerInstance } from 'pptx-vanilla-viewer';
const viewer: PptxViewerInstance = createPptxViewer(host, { source });Custom-shell collaboration
createStore(createInitialViewerState()), renderSlideStage, loadPresentation and createCollaborationShell are public root exports for applications that own the chrome. The shell reuses the existing collaboration controller, not a second provider.
import {
createCollaborationShell,
createInitialViewerState,
createStore,
} from 'pptx-vanilla-viewer';
const store = createStore(createInitialViewerState());
const shell = createCollaborationShell({
document,
store,
getHandler: () => loadedPresentation?.handler ?? null,
getCanEdit: () => hostCanEdit,
getSourcePending: () => store.get().loading,
getScale: () => zoom,
getSaveOptions: () => currentSaveOptions,
});
await shell.setConfig(collaboration);
// Begin the load AFTER attaching the session, before replacing the store's slides.
shell.controller.beginContentLoad('bootstrap');
// Load the source package and update the store here.
shell.controller.notifyContentLoaded('bootstrap');getState() exposes effective canEdit, connection status, remoteUsers and connectedCount. Pass the original host permission to getCanEdit, not the effective store.editable value. Call refresh() after host-only permission, loading or zoom changes; store/session changes refresh automatically. Mount cursorOverlay.el and selectionOverlay.el beside the scaled stage. destroy() removes only the shell's resources, leaving a borrowed document, awareness and provider intact.
This lower-level composition does not supply every built-in editor operation. The host owns selection, navigation, gestures and history. Native rich-text editing is available through openInlineEditor, canInlineEditElement and buildInlineTextCommitPatch. Pass { patcher: shell.controller.livePatcher, slideId } as the editor's collaboration option for an element actually owned by that slide. Check the current model with session.checkModel after replacement. Save must use its canonical readList() result and reject unfinished native input or composition; do not fall back to old model text. The exported overlayInlineTextSnapshot overlays that snapshot without committing the model.
Respect canInteractWithElement locks and the effective edit gate. On permission loss, retain only readAccepted() from a still-current session into the local model, then cancel the editor without a history entry or new shared write. commit() may defer while native input is unfinished, so forced teardown must call cancel(). Dispose the loaded handler and call revokeBlobUrls on its blob URLs when replacing the source or unmounting.
The Vanilla host-owned demo provides a working example using only public exports. See the session guide for persistence boundaries.
Slide thumbnail rail
createSlidesPane(container, options) mounts the rail of slide thumbnails that createPptxViewer shows beside the canvas, for a shell that renders its own canvas with renderSlideStage. It lists every slide (grouped by section when you pass sections) and marks the active row with aria-current="true". Clicking a thumbnail calls onSelectSlide(index); the rail never edits the deck itself. With canEdit, it adds a "New slide" footer, the thumbnail and section context menus and Enter-to-insert, and reports every command (add, add after, duplicate, delete, hide, sections) to your callbacks, so slide changes go through the same store and collaboration sync as your other edits.
import { createSlidesPane, loadPresentation } from 'pptx-vanilla-viewer';
const deck = await loadPresentation(bytes);
const pane = createSlidesPane(railHost, {
slides: deck.slides,
activeSlideIndex: 0,
canvasSize: deck.canvasSize,
mediaDataUrls: deck.mediaDataUrls,
headerFooter: deck.headerFooter,
customProperties: deck.customProperties,
firstSlideNumber: deck.firstSlideNumber,
colorScheme: deck.colorScheme,
fontScheme: deck.fontScheme,
formatScheme: deck.formatScheme,
tableStyleMap: deck.tableStyleMap,
canEdit: true,
onSelectSlide: (index) => showSlide(index),
onAddSlide: () => addSlideAfterCurrent(),
});
// Pass only what changed; a new active index moves the marker without redrawing thumbnails.
pane.update({ activeSlideIndex: 2 });
pane.destroy();Thumbnails are drawn with the canvas's inputs: pass the same theme schemes, table styles and registry as your renderSlideStage calls, and templateElementsBySlideId if you keep layout elements apart from each slide's own. Date, footer, document-property and slide-number fields resolve from headerFooter, customProperties and firstSlideNumber (p:presentation/@firstSlideNum), so a deck numbered from 45 shows "Slide 45" on its first thumbnail. The multi-selection commands (onDuplicateSlides, onDeleteSlides, onHideSlides) receive every selected index; createSlidesPaneBulkSlideOps lifts single-slide operations to them. The "Layout" entry of a slide's context menu makes that slide active and calls the optional onOpenLayoutGallery({ slideIndex, x, y }), since a custom shell renders its own Layout picker. The rail has no collapse control; hide or remove pane.el yourself. It needs the full viewer stylesheet (pptx-vanilla-viewer/styles.css or getViewerCss()) and a .pptxv ancestor.
Single slide thumbnail
renderSlideThumbnail(options) (exported, with its SlideThumbnailOptions type, from the package root) draws one slide the way createSlidesPane draws it, for a host that keeps its own thumbnail strip, and returns the thumbnail's root element. It draws from the slide model, so it shows unsaved edits, and it is static: the stage is inert (no focus stops or pointer interaction), carries no editing contract and no data-element-id, so ids stay unique to your editing canvas. A slide with a transition other than Cut shows the transition's name in a small badge in its top-right corner, as the thumbnail does in every binding (createSlidesPane draws no badge). Its options are document, slide, templateElements (the slide's layout and master elements, drawn beneath its own; default none) and previewWidth (pixels; default the rail thumbnail width; the height follows the deck's aspect ratio), plus these createSlidesPane options with the same meaning: canvasSize, mediaDataUrls, headerFooter, customProperties, firstSlideNumber, locale, colorScheme, fontScheme, formatScheme, tableStyleMap, t, registry and slides. So you can spread the options you give the pane:
import { disposePptxRenderStage, renderSlideThumbnail } from 'pptx-vanilla-viewer';
import type { SlidesPaneOptions } from 'pptx-vanilla-viewer';
function drawStrip(strip: HTMLElement, paneOptions: SlidesPaneOptions): void {
// Retire the previous thumbnails' render subscriptions before replacing them.
disposePptxRenderStage(strip);
strip.replaceChildren(
...paneOptions.slides.map((slide) => {
const item = document.createElement('li');
item.style.width = '120px';
item.append(
renderSlideThumbnail({
...paneOptions,
document,
slide,
templateElements: paneOptions.templateElementsBySlideId?.[slide.id],
previewWidth: 120,
}),
);
return item;
}),
);
}The thumbnail fills its container's width and is as tall as previewWidth at the deck's aspect ratio, so give the container that width. Slides from loadPresentation already carry their layout and master elements, so leave templateElements unset for them. It is a snapshot: call it again when the slide changes (any of its fields: elements, background, transition, number, hidden, "Hide Background Graphics"), where you also call pane.update, and replace the old element. It needs the same stylesheet and .pptxv ancestor as the rail.
The returned element owns render subscriptions: a chart in it repaints when a picture colour sample resolves, through a listener shared by the whole document. Pass the element, or any ancestor, to disposePptxRenderStage (exported from the package root) before you replace or remove it, as drawStrip above does; otherwise the old chart stays subscribed until the next sample. The call is idempotent and removes no DOM. The same applies to a stage you draw yourself with renderSlideStage.
Loading
| Method | Signature | Description |
|---|---|---|
loadFile | (file: Blob | ArrayBuffer | Uint8Array) => Promise<void> | Load a presentation from bytes or a Blob/File (replaces the current one). |
loadUrl | (url: string) => Promise<void> | Fetch and load a presentation from a URL. |
dismissAllCompatToasts | () => void | Dismiss every compatibility warning toast of the current load, as the stack's "Dismiss all" button does. |
Both resolve once the presentation is rendered; failures surface through the onError callback. A deck with compatibility warnings opens a toast stack after each load; pass showCompatibilityToasts: false (see Options & Callbacks) to never show it.
Navigation
| Method | Signature | Description |
|---|---|---|
next / goNext | () => void | Go to the next slide (no-op on the last slide). |
prev / goPrev | () => void | Go to the previous slide (no-op on the first slide). |
goToSlide / goTo / setActiveSlideIndex | (index: number) => void | Jump to a zero-based slide index (clamped). |
getSlideCount | () => number | Number of slides in the loaded presentation (0 when none). |
getCurrentSlide / getActiveSlideIndex | () => number | Zero-based index of the visible slide. |
The aliases (goTo, goPrev, goNext, getActiveSlideIndex, setActiveSlideIndex) come from the shared PowerPointViewerAPI and behave identically to the vanilla-native names.
Zoom
| Method | Signature | Description |
|---|---|---|
getZoom | () => number | Editing zoom (1 = 100%) after fit resolution, also during a show. |
setZoom | (zoom: number) => void | Set an explicit zoom scale, clamped to 0.1 - 5 times the fit scale. |
zoomIn | () => void | Zoom in by one step. |
zoomOut | () => void | Zoom out by one step. |
zoomToFit | () => void | Fit the slide to the viewport. |
zoomReset | () => void | Reset zoom to 100%. |
Viewer mode
| Method | Signature | Description |
|---|---|---|
getMode | () => ViewerMode | The current mode, derived from state. |
setMode | (mode: ViewerMode) => void | Switch mode; see the mapping below. |
type ViewerMode = 'preview' | 'edit' | 'present' | 'master';setMode('present') enters presentation mode; 'edit' enables editing; 'master' enables editing and switches to the master view; 'preview' leaves presentation/master mode and disables editing.
Theming & localization
| Method | Signature | Description |
|---|---|---|
setTheme | (theme: ViewerTheme | undefined) => void | Apply a new viewer theme (pass undefined to reset to defaults). See Theming. |
setLocale | (locale: string) => void | Switch the UI locale (rebuilds the chrome labels). |
Chrome
| Method | Signature | Description |
|---|---|---|
setShowToolbar | (show: boolean) => void | Show or hide the toolbar on a live viewer (the showToolbar option). Only the chrome is rebuilt, as for setLocale: the deck, unsaved edits and the undo history are kept. |
setRibbonDisplay | (mode: 'always' | 'tabs' | 'fullScreen') => void | Set PowerPoint's Ribbon Display Options from the host: the docked ribbon, the tab row alone, or full-screen mode. onRibbonDisplayChange is not called for it. |
setRibbonAddIns | (tabs: readonly RibbonAddInTab[]) => void | Replace the host's ribbon tabs (the ribbonAddIns option); an empty list removes them. |
getRibbonDisplay | () => 'always' | 'tabs' | 'fullScreen' | The current Ribbon Display Options mode. |
Presentation mode
| Method | Signature | Description |
|---|---|---|
enterPresentation | () => Promise<void> | Enter presentation mode (real Fullscreen API). |
exitPresentation | () => Promise<void> | Exit presentation mode (Esc also exits). |
Entering and leaving fires the onPresentationChange callback.
Editing
Pass editable: true in the options (or call setEditable(true)) to turn on click-to-select, drag-to-move, resize/rotate handles, and double-click inline text editing directly in the DOM. These methods are the programmatic entry points around that interaction:
| Method | Signature | Description |
|---|---|---|
setEditable | (editable: boolean) => void | Enable or disable editing at runtime (disabling clears the selection). |
setReadOnly | (readOnly: boolean) => void | Make the deck read-only (true wins over editable) or lift that restriction at runtime. |
setEditTemplateMode | (enabled: boolean) => void | Target inherited master/layout elements on the current slide. |
undo | () => void | Undo the last edit (no-op when the undo stack is empty). |
redo | () => void | Redo the last undone edit (no-op when the redo stack is empty). |
canUndo / canRedo | () => boolean | Whether undo() / redo() would do anything. |
deleteSelected | () => void | Delete the selected element (no-op without a selection). |
getSelectedElementId | () => string | null | Id of the selected element, or null. |
isDirty | () => boolean | Whether the document has unsaved changes. |
Host-persisted Save
When the host serialises the deck and stores it itself (possibly slowly), use a revision token so edits made while the upload is in flight stay unsaved. Nothing reloads and undo history is kept.
| Method | Signature | Description |
|---|---|---|
getSaveRevision | () => number | The revision of the document now. It changes after every edit. |
getSaveSnapshot | () => Promise<{ revision: number; content: Uint8Array }> | Serialise the deck for the host. The document stays dirty and no save event fires. |
acknowledgeSave | (revision: number) => PptxSaveAcknowledgement | Tell the viewer the host persisted revision. |
Result types:
interface PptxSaveSnapshot {
readonly revision: number;
readonly content: Uint8Array;
}
type PptxSaveAcknowledgement =
| { readonly status: 'clean'; readonly revision: number }
| { readonly status: 'pending'; readonly revision: number; readonly currentRevision: number }
| { readonly status: 'stale'; readonly revision: number; readonly savedRevision: number }
| { readonly status: 'unknown'; readonly revision: number };acknowledgeSave returns one of:
{ status: 'clean' }:revisionis still current. The document is clean,onDirtyChange(false)fires and the crash-recovery copy is discarded (unless Options > Save keeps the last AutoRecover version).{ status: 'pending', currentRevision }: the revision is accepted but edits were made since. The document stays dirty and the recovery copy, which may hold those edits, is kept.{ status: 'stale' }: older than a revision already acknowledged. Ignored.{ status: 'unknown' }: not a revision this viewer issued. Ignored.
Never acknowledge a failed save: the document then simply stays dirty. Undoing back to the saved content is an edit like any other, so the document is dirty until the next save. Unlike getContent() in Svelte and vanilla, getSaveSnapshot() never clears the dirty flag.
const { revision, content } = await viewer.getSaveSnapshot();
try {
await host.persist(content);
viewer.acknowledgeSave(revision);
} catch {
// not acknowledged: the document stays dirty
}onChange fires after any mutation (move, resize, rotate, text edit, delete, undo, redo); onDirtyChange fires when the unsaved-edits flag flips; onSelectionChange fires when the selected element id changes.
Keyboard shortcuts, active whenever an element is selected and editing is enabled: Ctrl/Cmd+Z undo, Ctrl/Cmd+Shift+Z (or Ctrl+Y) redo, Delete/Backspace delete, Ctrl/Cmd+D duplicate, arrow keys nudge 1px (Shift+arrow for 10px), Escape deselect.
Saving & downloads
| Method | Signature | Description |
|---|---|---|
save | (format?: PptxSaveFormat) => Promise<Uint8Array> | Serialise the (edited) presentation (default 'pptx') and clear the dirty flag. |
getContent | () => Promise<Uint8Array> | Alias of save(): the serialized .pptx bytes (shared-API name). |
downloadAs | (format: PptxSaveFormat, fileName?: string) => Promise<void> | Save and trigger a browser download in a supported format (OpenXML, or legacy binary .ppt). |
downloadPptx | (fileName?: string) => Promise<void> | save() plus trigger a browser download (default presentation.pptx). |
type PptxSaveFormat = 'pptx' | 'ppsx' | 'pptm' | 'ppt';const viewer = createPptxViewer(host, { source, editable: true });
undoButton.addEventListener('click', () => viewer.undo());
redoButton.addEventListener('click', () => viewer.redo());
saveButton.addEventListener('click', () => void viewer.downloadPptx('edited.pptx'));Export & print
Raster export renders each slide off-screen at scale 1 and rasterises it with html2canvas-pro (dynamically imported, so the first call pays a one-time load cost). jspdf and the GIF encoder are also lazy-loaded. Only one export runs at a time; a call while one is in flight resolves as a no-op.
| Method | Signature | Description |
|---|---|---|
exportSlidePng | (index?: number) => Promise<void> | Export a slide as a PNG download (defaults to the current slide). |
copySlideAsImage | (index?: number) => Promise<void> | Copy a slide to the system clipboard as a PNG image. |
exportPdf | (options?: ExportPdfOptions) => Promise<void> | Export every slide as a multi-page PDF download (one slide per page). |
exportGif | (options?: ExportGifOptions) => Promise<void> | Export every slide as an animated GIF download (one frame per slide, shared pure-JS GIF89a encoder). |
exportVideo | (options?: ExportVideoOptions) => Promise<void> | Export every slide as a WebM video download (canvas stream recorded by MediaRecorder). |
exportJson | () => void | Serialize the deck to pptx-viewer-json and trigger a browser download (File > Export > Export as JSON). |
print | (options?: PrintOptions) => Promise<boolean> | Assemble the printable document and open it in a print window; false = popup blocked. |
All option interfaces are exported from the package root:
type ExportProgress = (current: number, total: number) => void;
interface ExportPdfOptions {
onProgress?: ExportProgress; // capture-phase progress: (currentSlide, totalSlides)
signal?: AbortSignal; // abort early; checked between slides
}
interface ExportGifOptions {
slideDurationMs?: number; // per-frame duration, default 2000
slideTimingsMs?: number[]; // per-slide overrides (e.g. rehearsed timings)
maxDimension?: number; // cap on the longer frame side, default 1920
onProgress?: ExportProgress;
signal?: AbortSignal;
}
interface ExportVideoOptions {
slideDurationMs?: number; // per-slide hold, default 3000
slideTimingsMs?: number[]; // per-slide overrides
fps?: number; // recording frame rate, default 30
videoBitsPerSecond?: number; // MediaRecorder bitrate, default 5,000,000
onProgress?: ExportProgress; // capture phase
onRecordProgress?: ExportProgress; // recording phase
signal?: AbortSignal;
}Downloads are named presentation-slide-<n>.png, presentation.pdf, presentation.gif, and presentation.webm. Aborting via signal rejects with an AbortError DOMException.
renderToCanvas
A standalone function exported from the package root (no viewer instance needed) that rasterises any DOM element to a Canvas:
import { renderToCanvas } from 'pptx-vanilla-viewer';
const canvas: HTMLCanvasElement = await renderToCanvas(element, { scale: 2 });
const dataUrl = canvas.toDataURL('image/png');function renderToCanvas(
element: HTMLElement,
options?: Partial<Html2CanvasOptions>, // the html2canvas-pro Options type
): Promise<HTMLCanvasElement>;The same html2canvas-pro wrapper React, Vue, Angular and Svelte export. Reach for it rather than calling html2canvas yourself: during the onclone phase it runs the shared CSS-preprocessing passes, which convert modern colour functions (oklch / oklab / lch / lab / color()) to sRGB and flatten backdrop-filter, mix-blend-mode and CSS 3D transforms. The viewer's theme tokens are authored in oklch, which html2canvas cannot parse on its own.
Print
print() covers slides, notes pages, handouts, and an outline view, assembled from the shared print module. PrintOptions is any subset of the shared PrintSettings (unspecified fields fall back to the defaults: all slides, landscape, full colour) plus progress/abort and a window override:
interface PrintOptions extends Partial<PrintSettings> {
onProgress?: ExportProgress;
signal?: AbortSignal;
openPrintWindow?: (htmlDocument: string) => boolean; // OpenPrintWindow
}
interface PrintSettings {
printWhat: 'slides' | 'handouts' | 'notes' | 'outline'; // default 'slides'
orientation: 'portrait' | 'landscape'; // default 'landscape'
colorMode: 'color' | 'grayscale' | 'blackAndWhite'; // default 'color'
frameSlides: boolean; // default false
slidesPerPage: 1 | 2 | 3 | 4 | 6 | 9; // handouts only, default 6
slideRange: 'all' | 'current' | 'custom'; // default 'all'
customRangeFrom: number; // 1-based, default 1
customRangeTo: number; // 1-based, default 1
}Popup blockers
The default opener uses window.open, which browsers typically only allow inside a user gesture: call print() from a click handler, or pass a custom openPrintWindow that writes into an iframe you own. When the popup is blocked the promise resolves false.
SVG export (standalone functions)
Vector export does not need the viewer instance; two pure functions work on the parsed core data (reach it via getHandler() or getSlides()):
import { exportSlideToSvg, exportAllSlidesToSvg } from 'pptx-vanilla-viewer';
exportSlideToSvg(slide, width, height, options?): string; // one slide as SVG markup
exportAllSlidesToSvg(data, options?): string[]; // PptxData in, one SVG string per slide
interface SvgExportOptions {
includeHidden?: boolean; // include hidden slides when exporting all, default false
slideIndices?: number[]; // 0-based subset; omitted = all slides
defaultFontFamily?: string;
defaultFontSize?: number; // points
}Slides & elements (data API)
The shared data surface for hosts that build their own UI. Slide getters return the actual typed PptxSlide[] / PptxElement[] model as read-only snapshots; mutations only flow back through the manipulation methods (which participate in undo/redo and fire onChange).
| Method | Signature | Description |
|---|---|---|
getSlides | () => readonly PptxSlide[] | The full slide array. |
getSlide | (index: number) => PptxSlide | undefined | One slide by zero-based index. |
getActiveSlide | () => PptxSlide | undefined | The currently active slide. |
addSlide | (afterIndex?: number) => void | Add a blank slide after the given index (default: at the end). |
deleteSlides | (indexes: number[]) => void | Delete slides at the given indexes (at least one slide is kept). |
duplicateSlides | (indexes: number[]) => void | Duplicate slides at the given indexes. |
moveSlide | (fromIndex: number, toIndex: number) => void | Move a slide to a new position. |
toggleHideSlides | (indexes: number[]) => void | Toggle the hidden flag on slides. |
getElements | (slideIndex?: number) => readonly PptxElement[] | Elements on a slide (default: active slide). |
getElementById | (elementId: string, slideIndex?: number) => PptxElement | undefined | One element by id. |
updateElement | (elementId: string, updates: Partial<PptxElement>) => void | Patch element properties (e.g. { x: 100, width: 300 }). |
updateElements | (updates: readonly ElementUpdate[], options?: ElementUpdateOptions) => Promise<void> | Update elements across slides in one undo step. |
deleteElements | (elementIds: string[]) => void | Delete elements by id from the active slide. |
duplicateElement | (elementId: string) => string | undefined | Duplicate an element; returns the new element's id. |
getSelectedElementIds | () => string[] | Ids of the currently selected elements. |
selectElements | (ids: string[]) => void | Programmatically select elements. |
clearSelection | () => void | Clear the selection. |
Inserting an element
addElement(element: PptxElement): string | undefined appends a defensive copy to the active editable slide and selects it, returning its fresh ID. Coordinates are preserved; group descendants also receive fresh IDs. Pending text is committed through the existing editor path, with normal dirty-state and Undo/Redo behavior. Synchronous edits may share a history entry, but all insertions are retained. It returns undefined while loading, after a load error, without an active slide, or in read-only/protected, preview, presentation, or template/master editing modes.
Use a self-contained model or one from the current document. With a loaded viewer in edit mode:
import { createImageElement } from 'pptx-viewer-core';
const image = createImageElement(pngDataUrl, { x: 40, y: 40, width: 160, height: 90 });
const insertedId = viewer.addElement(image);This method does not install clipboard listeners, fetch remote URLs, choose image dimensions, or import another document's relationships. A host-owned paste handler can read an image and call it. For a new data-URL image, use the factory above without inventing an imagePath, which denotes an existing archive part.
Loading a local image
The package also exports createImageElementFromFile(file, canvasSize, signal?). Given a local File or Blob, the slide size in pixels, and an optional AbortSignal:
import { createImageElementFromFile } from 'pptx-vanilla-viewer';
const image = await createImageElementFromFile(file, canvasSize, signal);The helper preserves the image bytes and returns a centred ImagePptxElement, fitted to the slide without upscaling. It resolves null for invalid/unreadable images or dimensions, cancellation, or unavailable browser APIs. The helper does not use browser APIs until called; decoding requires those APIs.
This only constructs an element: it does not change a deck, history, selection, or clipboard. After await, verify that the same document and destination slide are still active and editable, then pass a non-null result to addElement. Abort pending work when that destination is abandoned. A slide ID alone is not a document identity, and decoding success does not guarantee that every browser image format round-trips in PowerPoint. No automatic paste listener is installed.
Collaboration
| Method | Signature | Description |
|---|---|---|
startCollaboration | (config: CollaborationInput) => Promise<void> | Start (or restart) a real-time session; resolves once the transport is created. Status arrives via onCollaborationStatus. |
stopCollaboration | () => void | Stop the active session (no-op when none is running). |
getCollaborationState | () => CollaborationState | The shared collaboration state (the off state when no session is active). |
getCollaborationStatus | () => ConnectionStatus | Current status: 'disconnected' | 'connecting' | 'connected' | 'error' ('disconnected' when inactive). |
See Options for CollaborationConfig and the wire-format caveat.
Autosave
| Method | Signature | Description |
|---|---|---|
autosaveNow | () => Promise<void> | Force an immediate snapshot (no-op when autosave is disabled). |
setAutosaveEnabled | (enabled: boolean) => void | Enable or disable recovery autosave without rebuilding. |
isAutosaveEnabled | () => boolean | Whether recovery autosave is currently enabled. |
Extension & escape hatches
| Method | Signature | Description |
|---|---|---|
getRegistry | () => ElementRendererRegistry | The element-renderer registry in effect (extension point). See Element Renderers. |
getHandler | () => PptxHandler | null | The live pptx-viewer-core handler for the loaded file (or null). |
Core escape hatch
getHandler() exposes the full pptx-viewer-core PptxHandler behind the viewer, which allows operations the viewer itself does not surface: convert the deck to Markdown or read parts of the underlying archive. (For plain serialisation prefer the instance's own save() / getContent(), which also clear the dirty flag.)
const handler = viewer.getHandler();
if (handler) {
const bytes = await handler.save(handler.pptxData!.slides); // Uint8Array
}pptx-vanilla-viewer/internals: slide-transition helpers
The framework-agnostic logic every binding uses lives in ooxml-ui/pptx; the private pptx-viewer-shared package is only its compatibility facade. A host embedding its own presentation surface still needs the transition resolver/keyframes and the DOM-level overlay driver, so they are re-exported from the pptx-vanilla-viewer/internals subpath instead:
import {
resolveSlideTransition,
resolveTransitionDurationMs,
SLIDE_TRANSITION_KEYFRAMES,
playTransitionOverlay,
} from 'pptx-vanilla-viewer/internals';resolveSlideTransition maps a PptxSlideTransition to the CSS animation shorthands for the outgoing/incoming layers; resolveTransitionDurationMs resolves its effective duration (ms), honoring an authored duration, the legacy spd token, and PowerPoint's own defaults; SLIDE_TRANSITION_KEYFRAMES (alias SLIDE_TRANSITION_KEYFRAMES_CSS) is the @keyframes block those animation names reference. playTransitionOverlay is the Vanilla binding's DOM-driven equivalent of the other bindings' transition overlay component (there is no component model to render one against here): it stacks the outgoing/incoming stage snapshots and drives the CSS animation directly. Also exported: getSlideTransitionAnimations, getCinematicTransitionAnimations, getP14TransitionAnimations, CINEMATIC_TRANSITION_KEYFRAMES / P14_TRANSITION_KEYFRAMES_ALL, resolveDirection / resolveDirection8 / resolveOrientation / resolveWheelSpokeCount, and the supporting constants (RANDOM_ELIGIBLE_TYPES, INSTANT, DEFAULT_TRANSITION_DURATION_MS, DEFAULT_MORPH_DURATION_MS, TRANSITION_SPEED_DURATION_MS, EASE, WHEEL_SPOKE_COUNTS).
As with every other binding's internals entry, this is not covered by semver: reach for it only when the public pptx-vanilla-viewer API genuinely cannot do what you need, and pin an exact version if you depend on it.
UI customization
The handle also carries the whole ViewerCustomizationApi, so the chrome can be customised while the viewer runs. Each call re-renders the affected UI immediately.
viewer.hideRibbonTab('draw');
viewer.lockSetting('general.userName', 'Ada Lovelace');
viewer.hideContextMenuCommand('delete');
viewer.remapShortcut('duplicate', 'Mod+Shift+D');
viewer.setFeatureEnabled('ai', false);
viewer.setPanelVisible('notes', false);
viewer.updateCustomization({ hiddenDialogs: ['print'] });
const current = viewer.getCustomization();| Method | Effect |
|---|---|
getCustomization() / setCustomization(c) / updateCustomization(patch) / resetCustomization() | Read, replace, merge or clear the whole ViewerCustomization. |
hideRibbonTab / showRibbonTab, hideToolbarButton / showToolbarButton | Ribbon tabs and top-level toolbar buttons. |
hideOptionsPage, hideOptionsSection, hideSetting (and show*) | File > Options pages, sections and settings. |
lockSetting(id, value, hidden?) / unlockSetting(id) / setSettingDefault(id, value) | Pin a setting (read-only or hidden) or set a host default. |
hideBackstagePage / hideBackstageCard (and show*) | File tab pages and action cards. |
hideContextMenuCommand / hideCanvasContextMenuCommand (and show*) | Element and empty-canvas right-click entries. |
disableShortcut / enableShortcut / remapShortcut | Editor keyboard shortcuts. |
setPanelVisible, setFeatureEnabled, setDialogAvailable | Panels, feature areas (AI, collaboration, ...) and dialogs. |
The full id reference and recipes are in the UI Customization guide.
Teardown
| Method | Signature | Description |
|---|---|---|
destroy | () => void | Tear down DOM, listeners, Blob URLs, and the core handler. |
Example: external controls
import { createPptxViewer } from 'pptx-vanilla-viewer';
const viewer = createPptxViewer(document.getElementById('host')!, {
source: '/deck.pptx',
showToolbar: false,
showThumbnails: false,
onSlideChange: (i) => {
counter.textContent = `Slide ${i + 1} of ${viewer.getSlideCount()}`;
},
});
prevButton.addEventListener('click', () => viewer.prev());
nextButton.addEventListener('click', () => viewer.next());
fitButton.addEventListener('click', () => viewer.zoomToFit());
presentButton.addEventListener('click', () => void viewer.enterPresentation());
pdfButton.addEventListener('click', () => void viewer.exportPdf());Openable file kinds
The package root re-exports the shared answer to "can the viewer open this file?", so a host's drop target and its <input accept> cannot disagree with the loader. Hand-rolled endsWith chains drift: every demo in this repo once shipped .pptx,.ppt,.json, which refused on drop a .pptm that File > Open inside the viewer accepted without complaint.
import {
PPTX_OPEN_ACCEPT,
PRESENTATION_OPEN_EXTENSIONS,
isSupportedPresentationFile,
isLegacyBinaryPresentation,
presentationBaseName,
savedPresentationFileName,
type SavedPresentationFormat,
} from 'pptx-vanilla-viewer';| Export | Type | Description |
|---|---|---|
PPTX_OPEN_ACCEPT | string | Ready-made <input type="file" accept> value: .pptx,.ppsx,.pptm,.potx,.ppt,.json. |
PRESENTATION_OPEN_EXTENSIONS | readonly string[] | The same list unjoined, for a drop target that wants to test extensions itself. |
isSupportedPresentationFile | (name?: string | null) => boolean | Cheap pre-filter for a picked or dropped file name. Extension-only; the real answer is the loader's sniff. |
isLegacyBinaryPresentation | (name?: string | null) => boolean | True for the binary PowerPoint 97-2003 family (.ppt / .pps / .pot). The viewer reads all three and writes .ppt; .pps and .pot are read-only. |
presentationBaseName | (name?: string | null, fallback?: string) => string | The file-name stem, directories and any loadable extension removed (a path like decks/report.ppt becomes report). |
savedPresentationFileName | (name?: string | null, format?: SavedPresentationFormat) => string | The name a saved copy should be offered under: report.ppt becomes report.pptx. |
SavedPresentationFormat | 'pptx' | 'ppsx' | 'pptm' | 'ppt' | The formats the save path can produce. Binary .ppt is a save target, chosen explicitly; .pps and .pot are never written. |
savedPresentationFileName is the one that matters on Save As. A regular Save As writes an OpenXML package under a .pptx name, so a legacy source extension is replaced: keeping .ppt would hand the user a .ppt whose bytes are a ZIP, which PowerPoint refuses to open. Choosing 'ppt' explicitly writes the binary format under the .ppt name.