PPTX.js: PowerPoint Viewer and Editor in Vanilla JavaScript

Category: Javascript , Recommended | November 20, 2026
Authormeshesha
Last UpdateNovember 20, 2026
LicenseMIT
Views0 views
PPTX.js: PowerPoint Viewer and Editor in Vanilla JavaScript

PPTX.js v2 is a JavaScript library for viewing and editing PowerPoint (.pptx) files in the browser.

It renders slides as HTML and SVG, offers scrolling and slideshow views, and exports edited presentations to PPTX or ODP.

The library is the TypeScript rewrite of the original jQuery PPTX.js plugin. It currently runs in vanilla JavaScript with fflate as its only runtime dependency.

Features

  • Rendering for PowerPoint charts, tables, images, and speaker notes.
  • Scrolling slide list and slideshow modes with adjustable scaling.
  • Keyboard navigation, fullscreen playback, autoplay, and transitions.
  • Text, shape, picture, and slide editing with undo and redo.
  • PPTX and ODP export from the editor or document API.
  • HTML rendering APIs for browsers, Node.js, and Web Workers.
  • Right-to-left text and viewer controls.
  • React, Vue, Angular, and Web Component integrations.

How To Use It

1. Install PPTX.js v2

Install the package via NPM.

npm install @meshesha/pptxjs

For a plain HTML page, load the UMD build from a CDN. It exposes window.PPTXjs and injects the viewer styles:

<script src="https://unpkg.com/@meshesha/pptxjs/dist/pptxjs.umd.js"></script>

2. Display a PowerPoint File

Use mode: "slideshow" for one slide at a time, or "list" for a scrolling slide list.

<div id="pptx-slides" style="min-height: 420px"></div>
<script src="https://unpkg.com/@meshesha/pptxjs/dist/pptxjs.umd.js"></script>
<script>
  const viewer = new PPTXjs.PptxViewer("#pptx-slides", {
    mode: "slideshow",
    scale: "contain",
    slideshow: {
      nav: true,
      transition: "fade"
    }
  });
  viewer.load("/presentations/sample.pptx").catch(console.error);
</script>

3. Preview a PPTX File Selected by the Visitor

Use load(file) with a file input to preview a local .pptx file. The method also accepts a Blob, ArrayBuffer, or typed array.

<input id="pptx-file" type="file" accept=".pptx">
<div id="local-pptx" style="min-height: 420px"></div>
<script src="https://unpkg.com/@meshesha/pptxjs/dist/pptxjs.umd.js"></script>
<script>
  const viewer = new PPTXjs.PptxViewer("#local-pptx");
  const input = document.querySelector("#pptx-file");
  input.addEventListener("change", async () => {
    const file = input.files[0];
    if (!file) return;
    try {
      await viewer.load(file);
    } catch (error) {
      console.error("Could not open presentation:", error);
    }
  });
</script>

4. Configure a Slideshow

The slideshow options control autoplay, looping, navigation, and transitions.

<div id="slides" style="height: 500px"></div>
import { PptxViewer } from "@meshesha/pptxjs";
const viewer = new PptxViewer("#slides", {
  mode: "slideshow",
  slideshow: {
    first: 1,
    autoplay: 5,
    loop: true,
    random: false,
    transition: "slide",
    transitionDuration: 0.4
  }
});
await viewer.load("/presentations/training.pptx");

5. Edit and Export a Presentation

PptxEditor includes slide thumbnails, drag-to-move and resize handles, inline text editing, formatting, and picture and shape insertion. The editor can reposition tables, charts, and SmartArt, but cannot edit their contents.

<div id="pptx-editor" style="height: 600px"></div>
<button id="save-pptx" type="button" disabled>Download PPTX</button>
<script src="https://unpkg.com/@meshesha/pptxjs/dist/pptxjs.umd.js"></script>
<script>
  const editor = new PPTXjs.PptxEditor("#pptx-editor", {
    fileName: "edited-presentation",
    toolbar: true,
    thumbnails: true
  });
  const download = document.querySelector("#save-pptx");
  editor.load("/presentations/sample.pptx")
    .then(() => { download.disabled = false; })
    .catch(console.error);
  download.addEventListener("click", () => editor.download("pptx"));
</script>

6. Edit Slides Programmatically

Use PresentationDocument to edit a PPTX template programmatically. In a browser module, load the file, add a text box, and download the updated presentation.

import { PresentationDocument, exportPptx } from "@meshesha/pptxjs";
const response = await fetch("/presentations/template.pptx");
if (!response.ok) throw new Error(`PPTX download failed: ${response.status}`);
const doc = await PresentationDocument.load(await response.arrayBuffer());
const id = doc.addTextBox(
  0,
  { x: 80, y: 60, width: 420, height: 70 },
  "Quarterly update",
  { size: 32, bold: true }
);
doc.setShapeFill(0, id, "#F3F5F8");
const blob = exportPptx(doc);
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "quarterly-update.pptx";
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);

7. Render PPTX Slides in Node.js

Node.js 18 or later supports headless rendering. Use renderToHtmlString() to save the presentation as an HTML file with its styles included. The renderer also works in Web Workers.

import { renderToHtmlString } from "@meshesha/pptxjs";
import { readFile, writeFile } from "node:fs/promises";
const pptx = await readFile("deck.pptx");
const slides = await renderToHtmlString(pptx);
const html = `<!doctype html><html><head><meta charset="utf-8"></head><body>${slides}</body></html>`;
await writeFile("deck.html", html);

All Configuration Options

Viewer Options

Pass these options as the second argument to new PptxViewer(container, options).

OptionDescription
mode"list" (default) or "slideshow".
scale"fit" (default) fits width; "contain" fits available width and height; a number uses a fixed multiplier (1 = 100%).
slideshowObject containing the slideshow settings in the next table.
keyboardtrue (default) responds when the viewer has focus; "global" enables page-wide shortcuts; false disables them.
showProgresstrue (default) displays loading progress.
incrementaltrue (default) yields between slides during rendering.
gap24 (default), spacing between slides in list mode, in pixels.
limits{ maxUncompressedSize, maxEntries }, default maximum 512 MiB uncompressed and 20,000 archive entries.
fetchOptionsRequestInit settings for fetching a presentation URL, such as headers and credentials.
textDirection"file" (default), "auto", or "rtl" for text without declared direction.
dir"auto" (default), "ltr", or "rtl" for the viewer controls and navigation direction.
themeProcesstrue (default), false, or "colorsAndImageOnly" to control master/layout rendering.
mediaProcesstrue (default) renders embedded video and audio.
externalMediafalse (default) shows links/posters for external media; true enables sandboxed embeds.
skipHiddenSlidesfalse (default) includes hidden slides; true skips them.
slidesArray of 1-based slide numbers to render, such as [1, 3]; default is all slides.
incSlide{ width?, height? } adds pixel adjustments to slide dimensions.
idPrefixPrefix for generated element IDs; automatically assigned by default.
measureHtmlWidth(html) => number to override text-width measurement.
onProgress(done, total) => void progress callback.
onWarning(warning) => void for nonfatal rendering issues.

Slideshow Options

OptionDescription
first1 by default; starting slide number (1-based).
navtrue by default; show the navigation toolbar.
showSlideNumbertrue by default; show the current and total slide numbers.
autoplayfalse by default; a number sets seconds between slides.
loopfalse by default; return to the beginning after the last slide.
randomfalse by default; select slides randomly during autoplay.
transition"fade" by default; also accepts "none", "slide", "zoom", and "random".
transitionDuration0.4 by default, in seconds.
backgroundCSS background color for the slideshow/fullscreen stage.

Editor Options

new PptxEditor(container, options) accepts the applicable viewer rendering options, excluding mode, keyboard, and slideshow, plus the following:

OptionDescription
toolbartrue (default) shows the editor toolbar.
thumbnailstrue (default) shows the slide thumbnail panel.
readOnlyfalse (default); true permits viewing and selection but disables edits.
fileName"presentation" (default), the base name used for downloads.

JavaScript API Reference

Viewer Methods

Readable viewer properties include slideCount, currentIndex, currentMode, playing, scale, result, package, element, id, and isRtl. result contains the most recent RenderedPresentation.

MethodDescription
load(source)Loads a URL, File, Blob, ArrayBuffer, or typed-array source; returns Promise<RenderedPresentation>. A newer load aborts the previous one.
renderPackage(pkg, { startIndex? })Renders an already opened PptxPackage.
rerenderSlide(index)Re-renders one slide after editing; returns the slide element or null.
goTo(index)Navigates to a slide using a 0-based rendered-slide index.
next(), prev()Moves forward or backward one rendered slide.
first(), last()Moves to the first or last rendered slide.
play(seconds?), pause()Starts autoplay with optional interval or pauses it.
setMode(mode)Switches between "list" and "slideshow".
setOptions(partial)Updates viewer settings at runtime.
enterFullscreen(), exitFullscreen()Enters or exits fullscreen.
toggleFullscreen()Toggles fullscreen.
getSlideElement(index)Returns a rendered slide element or null.
on(event, handler), off(event, handler)Subscribes/unsubscribes to events; on() returns an unsubscribe function.
destroy()Releases viewer markup, listeners, timers, and object URLs.

Viewer Events

Subscribe with viewer.on("event", handler).

EventPayload
loadstart{ source }
progress{ done, total, ratio }
load{ presentation }
error{ error }
warning{ warning }
slidechange{ index, slide }
sliderender{ index, element }
modechange{ mode }
fullscreenchange{ fullscreen }
const unsubscribe = viewer.on("slidechange", ({ index }) => {
  console.log("Slide index:", index);
});
// Call unsubscribe() when your application no longer needs this listener.

Editor Methods and Events

Editor events: load ({ slides }), error ({ error }), selectionchange ({ selection, shape }), slidechange ({ index }), and change ({ label }).

Method or propertyDescription
load(source)Opens a presentation for editing.
open(doc)Opens an existing PresentationDocument.
document, viewerThe editable model and embedded viewer instances.
select(selection), selectedSelects { slide, id } or clears selection with null; reads current selection.
goToSlide(index), currentSlideNavigates between editor slides and reports the current index.
undo(), redo()Reverses or reapplies editing actions.
exportPptx(), exportOdp()Returns exported Blob files.
download(format, fileName?)Downloads "pptx" or "odp", optionally with a custom name.
on(event, handler)Listens for editor events.
destroy()Cleans up the editor.

PresentationDocument Methods

Create a document with await PresentationDocument.load(source) or new PresentationDocument(pkg).

getShape() returns id, name, kind, bounds, rotation, placeholder, geometry, fill, paragraphs, and text.

Shape kinds include shape, textbox, picture, table, chart, diagram, group, connector, media, and other.

TextParagraph entries contain runs and optional align, level, and rtl.

Each TextRun supports text, bold, italic, underline, size, color, and font.

Method or propertyDescription
slides(), slideCountReturns slide references in presentation order and the slide count.
slideSize()Returns slide width and height in CSS pixels.
addSlide(afterIndex?, layoutOf?)Inserts a slide and returns the new slide index.
duplicateSlide(index)Duplicates a slide and returns the new index.
moveSlide(from, to)Reorders slides.
deleteSlide(index)Deletes a slide and its notes page.
setSlideHidden(index, hidden)Changes the hidden status of a slide.
getNotes(index)Returns speaker notes as text.
getShapes(slide), getShape(slide, id)Reads shapes on a slide or one shape by ID.
setShapeBounds(slide, id, bounds)Changes position and/or dimensions.
setShapeRotation(slide, id, degrees)Sets shape rotation.
deleteShape(slide, id)Deletes a shape.
duplicateShape(slide, id, dx?, dy?)Duplicates a shape and returns its new ID; default offset is 16 pixels on each axis.
reorderShape(slide, id, direction)Accepts "front", "back", "forward", or "backward".
setShapeText(slide, id, text)Sets plain text or TextParagraph[] content.
setTextStyle(slide, id, style)Applies bold, italic, underline, size, color, font, or align; null removes a property.
setShapeFill(slide, id, color)Sets a hex color or null for no fill.
setShapeLine(slide, id, color, widthPx?)Sets the shape outline color and optional width.
addTextBox(slide, bounds, text?, style?)Adds a text box and returns its ID.
addShape(slide, geometry, bounds, style)Adds a PowerPoint preset shape and returns its ID.
addImage(slide, bytes, mimeOrExt, bounds?)Adds an image and returns its ID.
undo(), redo()Undoes or redoes an editing step.
canUndo, canRedoReports whether undo or redo is available.
undoLabel, redoLabelLabels for the next undo/redo actions.
undoLimitHistory limit, default 100.
transact(change, fn)Groups edits into one undoable step and rolls them back if fn throws.
on("change" | "undo" | "redo", handler)Subscribes to document changes and history actions. The change event carries { type, index?, label }.
toPptx()Serializes the document to Uint8Array.

Headless Rendering and Export Functions

The RenderedPresentation result includes width, height, slides, css, thumbnail?, appVersion, and renderTime. Each RenderedSlide contains number, file, hidden, html, notes, and optional error.

exportOdp() accepts includeMasterShapes: true, includeNotes: true, skipHiddenSlides: false, and textDirection: "file" by default.

Function or constantDescription
loadPptx(source, options?)Loads a PptxPackage with optional limits, fetchOptions, and signal.
renderToHtml(source, options?)Renders to a RenderedPresentation containing slides, css, width, and height.
renderToHtmlString(source, options?)Returns slides and styles as one HTML string.
renderPresentation(pkg, options?)Synchronously renders an opened package.
listSlides(pkg)Returns slide metadata.
readNotes(pkg, slideFile)Returns speaker notes for a slide.
exportPptx(docOrPkg, options?)Returns a PPTX Blob; pruneUnusedMedia defaults to true.
exportPptxBytes(docOrPkg, options?)Returns PPTX bytes as Uint8Array.
exportOdp(docOrPkg, options?)Returns an ODP Blob; options are listed below.
exportOdpBytes(docOrPkg, options?)Returns ODP bytes as Uint8Array.
PPTX_MIME, ODP_MIMEMIME-type constants for exported files.
BASE_CSSBase renderer stylesheet, useful when assembling headless HTML.

Chart and Package Utilities

UtilityDescription
parseChart(chartSpaceXml, resolveFill)Parses a chart XML part into a chart model.
renderChartSvg(model, options)Returns SVG with width, height, and optional palette and fontFamily.
DEFAULT_PALETTEDefault color palette for chart SVGs.
PptxPackage.fromBytes(bytes, limits?)Opens a PPTX archive from bytes with optional safety limits.
pkg.list(), pkg.has(path)Lists or checks package entries.
pkg.bytes(path), pkg.text(path), pkg.xml(path)Reads binary, text, or XML entry content.
pkg.setBytes(path, data), pkg.setText(path, text)Sets package entries.
pkg.delete(path), pkg.clone(), pkg.toZip()Removes an entry, clones the package, or serializes it.

Error Codes

CodeMeaning
INVALID_FILESource is not a readable PowerPoint file.
LIMIT_EXCEEDEDA package size or entry limit was exceeded.
FETCH_FAILEDA request failed or returned HTTP status 400 or greater.
RENDER_WARNINGA slide had a nonfatal rendering issue.
EXPORT_FAILEDExport failed or an editing method received invalid data.
ABORTEDA newer load superseded an earlier one, or loading was stopped.

Web Components and Framework Adapters

Register the Web Components once in a module project. The UMD browser build registers them automatically:

import { defineCustomElements } from "@meshesha/pptxjs";
defineCustomElements();
<pptx-viewer src="/presentations/sample.pptx"
             mode="slideshow" scale="fit" transition="slide"
             autoplay="5" loop></pptx-viewer>
<pptx-editor src="/presentations/sample.pptx"
             style="display:block;height:600px"></pptx-editor>
Web Component APIDescription
<pptx-viewer> attributessrc, mode, scale, transition, autoplay, and loop.
<pptx-editor> attributesrc.
options propertySet ViewerOptions or EditorOptions before connecting the element.
source property (viewer)Accepts a URL, File, Blob, or byte input.
viewer, editor propertiesExpose the component instances.
Custom eventspptx-load, pptx-error, pptx-slidechange (viewer), and pptx-change (editor).
defineCustomElements(prefix?)Registers the default tags, or uses a custom tag prefix.

React projects can import PptxViewer and PptxEditor from @meshesha/pptxjs/react. Both accept src, options, className, and style. The viewer supports onLoad, onError, and onSlideChange; the editor supports onLoad, onError, onChange, and onSelectionChange. Refs expose the underlying instances. options is read on mount.

Vue projects can import both components from @meshesha/pptxjs/vue. They accept src and options. The viewer emits load, error, and slidechange, and the editor emits load, error, change, and selectionchange. app.use(PptxPlugin) registers both globally.

Angular projects can call definePptxElements() from @meshesha/pptxjs/angular and add CUSTOM_ELEMENTS_SCHEMA to the host component.

Styling Hooks

PPTX.js v2 uses inline positioning styles and injects a scoped stylesheet. A restrictive Content Security Policy must permit inline styles (style-src 'unsafe-inline'), even when you include @meshesha/pptxjs/style.css.

SelectorPurpose
.pptxjs-viewerViewer root.
.pptxjs-toolbar, .pptxjs-btnSlideshow controls and buttons.
.pptxjs-counterSlide counter.
.pptxjs-progress, .pptxjs-progress-barProgress UI.
.pptxjs-slides, .pptxjs-slide-wrapSlide list and slide wrappers.
.pptxjs-errorRendering error display.
.pptxjs-mode-list, .pptxjs-mode-slideshow, .pptxjs-fullscreenMode and fullscreen classes.
.pptx-shape[data-shape-id]Wrapper for a top-level PowerPoint shape.

Migrating from the Original jQuery PPTX.js

PPTX.js v2 replaces the original plugin’s D3.js, NVD3, JSZip, FileReader.js, and slideshow assets with a single browser build. The optional jQuery adapter preserves the old pptxToHtml() entry point for existing applications.

For the original jQuery implementation, see Convert PPTX File To HTML – jQuery PPTX.js for its v1 live demo and download. The following mappings apply when migrating to the v2 class API.

v1 usagev2 equivalent
$("#result").pptxToHtml({ pptxFileUrl: url })viewer.load(url)
fileInputIdPass the chosen File to viewer.load(file).
slideMode: truemode: "slideshow"
slidesScale: "50"scale: 0.5
keyBoardShortCut: truekeyboard: "global" for page-wide shortcuts.
slideModeConfig.autoSlideslideshow.autoplay
slideModeConfig.randomAutoSlideslideshow.random
slideModeConfig.transitionslideshow.transition ("slid" becomes "slide"; "default" becomes "none").
slideModeConfig.transitionTimeslideshow.transitionDuration
slideModeConfig.first, nav, loop, showSlideNum, backgroundslideshow.first, nav, loop, showSlideNumber, background.
mediaProcess, themeProcess, incSlideAvailable in v2 with the same option names.
jsZipV2, slideType: "revealjs", revealjsPath, revealjsConfig, navTxtColor, showPlayPauseBtnRemoved in v2.

You can keep the legacy jQuery call by installing the adapter:

import $ from "jquery";
import { installJQueryPlugin } from "@meshesha/pptxjs/jquery";
installJQueryPlugin($);
$("#result").pptxToHtml({
  pptxFileUrl: "/presentations/sample.pptx",
  slideMode: true
});

Compatibility and Limitations

  • EMF and WMF graphics cannot be displayed directly by browsers.
  • ODP conversion turns charts into SVG images and cannot preserve slide animations, embedded media, or WordArt effects.

Alternatives and Related Resources

You Might Be Interested In:


Leave a Reply