dom-to-pptx

repository·master·Indexed 43 days ago

https://github.com/atharva9167j/dom-to-pptx

A client-side library and CLI tool that converts HTML elements into fully editable PowerPoint (.pptx) slides. Version 2.1.2 transforms DOM structures into pixel-accurate content, preserving CSS Flexbox/Grid, gradients, shadows, and typography as native PowerPoint shapes. It includes a headless exporter via Puppeteer, a skills installer for AI agents (Claude Code, Gemini, Cursor, Windsurf), and support for declarative animations and transitions using CSS classes.

Tokens
48.8K
Snippets
106
Records
162
Agent score
56%

What's inside dom-to-pptx

  1. Understand the dom-to-pptx architecture and data flow

    master

    The dom-to-pptx ecosystem follows a layered pipeline architecture that transforms web content into PowerPoint presentations.

    1. Input Layer

    Consumes the DOM Tree (via elements, selectors, or arrays), CSS (computed and external styles), and user-provided Export Options (dimensions, scale, fonts, etc.).

    2. Core Engine (src/index.js)

    • exportToPptx(): The primary entry point for all exports.
    • processSlide(): The traversal engine that walks the DOM.
    • prepareRenderItem(): An item factory that converts DOM nodes into renderable objects.
    • RenderQueue: Manages both synchronous and asynchronous tasks to feed data into PptxGenJS.

    3. Analysis & Layout (src/utils.js)

    Handles the heavy lifting of DOM inspection, including:

    • Text Parsing: collectTextParts() extracts rich text; isTextContainer() identifies text nodes.
    • Layout: getPadding() and margin creation functions.
    • Styling: parseColor() for RGB/Alpha conversion and FontDetection for resolving CSS font faces.
    • Metadata: extractSpeakerNotesFromElement() for presentation notes.

    4. Font Embedding Pipeline (src/font-embedder.js)

    Detects fonts via getAutoDetectedFonts(), classifies variants, and uses a Wasm/opentype.js converter to transform fonts into EOT format for injection into the PPTX archive.

    5. Post-Processing Normalizer (src/pptx-normalizer.js)

    Uses JSZip to decompress the generated archive and applies critical patches:

    • ZReorder: Sorts shape Z-indices (<p:sp>).
    • AnimInject: Injects the <p:timing> animation tree.
    • TransInject: Injects slide transitions.
    • ContentTypeScrubber: Removes dangling <Override> tags to ensure file validity.
  2. How animations and transitions work in dom-to-pptx

    master

    Animations and transitions are applied declaratively using CSS classes. No additional JavaScript configuration is required for the export itself.

    To preview animations in the browser, you must include the animations.css and transitions.css stylesheets from the dom-to-pptx package.

    Browser Preview Setup

    Use domToPptx.applyBrowserAnimations(parentElement, options) to configure how animations behave in the browser:

    • enableClick: false (default): Animations play automatically in a sequenced timeline.
    • enableClick: true: Animations advance manually when the .slide element is clicked.

    Animation/Transition Utility Classes

    Class patternApplies toPurpose
    fade-in, zoom-in, fly-in, wipe-in (+ exit variants)ElementEntrance/exit animation style
    to-up, to-down, to-left, to-rightElementDirectional modifier
    animate-duration-[MS] / animate-delay-[MS]ElementCustom timing in milliseconds
    animate-trigger-on-click / animate-trigger-with / animate-trigger-afterElementClick-triggered, simultaneous, or sequential-chain timing
    letter / paragraphText elementCharacter-by-character or row-by-row builds
    slide-transition-fade, slide-transition-push, etc..slide containerSlide-to-slide transition style
    transition-duration-fast / transition-dur-[MS].slide containerCustom transition speed
    <!-- Required CSS for browser preview -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dom-to-pptx@latest/dist/animations.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dom-to-pptx@latest/dist/transitions.css" />
    
    <script>
      // Configure browser-side animation behavior
      domToPptx.applyBrowserAnimations(document.body, { enableClick: true });
    
      // Export as usual
      document.getElementById('export-btn').onclick = async () => {
        await domToPptx.exportToPptx(Array.from(document.querySelectorAll('.slide')), {
          fileName: 'animated-presentation.pptx',
        });
      };
    </script>
  3. How the dom-to-pptx pipeline works

    master

    The conversion process follows a four-stage pipeline:

    1. Initialization & Configuration: Determines slide dimensions, initializes the PptxGenJS instance, and sets up a WeakMap for text container caching to optimize performance.
    2. Slide Processing Loop: For each slide root, the engine:
      • Extracts CSS transitions and speaker notes (from <template data-pptx-notes> or [data-pptx-notes]).
      • Performs a synchronous DOM tree traversal to classify nodes (Text, UL/OL, TABLE, SVG/Canvas, or Shapes).
      • Executes parallel async tasks (like fetching image data URLs) using Promise.all.
      • Sorts the render queue by hierarchical Z-index and emits items to the PptxGenJS slide.
    3. Font Discovery & Embedding: If enabled, the system scans the CSSOM to find font families, fetches font buffers (TTF/OTF/WOFF/WOFF2), transcodes them via Wasm, and injects them into the PPTX package.
    4. Assembly & OpenXML Normalization: The raw PptxGenJS output is decompressed via JSZip. The pptx-normalizer.js performs "ZIP surgery" to fix Z-order, inject animation trees, inject slide transitions, and strip invalid <Override> references in [Content_Types].xml to prevent PowerPoint repair errors.
  4. Add presenter speaker notes using data-pptx-notes

    master

    To automatically generate PowerPoint speaker notes, annotate any slide root or nested element with the data-pptx-notes attribute.

    Example:

    <div class="slide" data-pptx-notes="This is the presenter note for this slide.">
      <h1>Slide Title</h1>
    </div>
  5. Implement Animations and Transitions

    master

    The dom-to-pptx engine supports both slide-level transitions and element-level animations.

    Slide Transitions

    Apply transition classes directly to .slide elements. Examples include slide-transition-fade, slide-transition-push, and slide-transition-wipe. You can control speed using classes like transition-duration-fast or custom transition-dur-[MS].

    Element Animations

    Apply animation classes to elements inside slides (e.g., fade-in, zoom-in, fly-in, wipe-in).

    Animation Control & Sequencing

    • Timing: Use animate-duration-[MS] and animate-delay-[MS] for fine-tuning.
    • Sequencing:
      • animate-trigger-on-click: Triggers animation on click.
      • animate-trigger-with: Triggers animation simultaneously with another element.
      • animate-trigger-after: Triggers animation sequentially after another element finishes.
    • Text Builds: Use the letter class for character-by-character typing effects, or the paragraph class for row-by-row reveals.

    Note: For a professional look, follow the Complete Staging Rule: if any element is animated, all foreground elements on that slide should be animated to avoid static/broken-looking content.

    <!-- Example of a sequenced animation sequence -->
    <h1 class="fade-in animate-duration-[1000]">
      Dynamic Presentation
    </h1>
    
    <p class="fly-in to-up animate-duration-[800] animate-delay-[200] animate-trigger-after">
      Powered by dom-to-pptx native animations
    </p>
  6. Handle SVG and Font URL resolution correctly

    master

    Two specific technical details can cause elements to be dropped or fonts to fail to load:

    • SVG Tag Names: In the browser DOM, SVG elements often use lowercase tag names (e.g., svg). Ensure your classification logic does not rely on case-sensitive checks like el.tagName === 'SVG', as this will cause SVGs to be misclassified as text and dropped.
    • Relative Font URLs: In external stylesheets, @font-face { src: url(...) } paths are relative to the stylesheet file, not the HTML document. When resolving font URLs, you must resolve them against the stylesheet's href or a provided baseHref to avoid 404 errors.
  7. Configure slide container invariants for reliable conversion

    master

    To ensure predictable layout and bounding-box calculations during PPTX export, every .slide root element must adhere to these requirements:

    1. Fixed Dimensions: Use fixed px dimensions. Recommended: 1920 × 1080 (or other 16:9 ratios like 1280 × 720). For portrait or custom aspect ratios, pass width and height in inches to the exportToPptx function.
    2. Positioning: Set position: relative on the slide root to allow absolute children to anchor correctly.
    3. Overflow: Set overflow: hidden to prevent child content from leaking outside the slide bounds.
    4. Avoid Ancestor Transforms: Do not place a .slide inside a parent element that has a CSS transform applied. This breaks the bounding-rect math used by the converter.
    /* Recommended Slide Root Setup */
    .slide {
      width: 1920px;
      height: 1080px;
      position: relative;
      overflow: hidden;
    }
  8. Data Invariants and Execution Contracts

    master

    When building extensions or consuming the API, adhere to these technical constraints to avoid corrupted PPTX files or unexpected behavior:

    State Isolation

    exportToPptx allocates an isolated _textContainerCache: new WeakMap() per invocation. Classification state does not leak across concurrent exports or subsequent runs.

    Text Box Inset Array Contract

    Note the difference in array ordering for margins:

    • pptxgenjs text shape margin: [lIns, rIns, bIns, tIns] (Left, Right, Bottom, Top).
    • pptxgenjs table cell margin: [marT, marR, marB, marL] (Top, Right, Bottom, Left).

    Font Slot Constraint

    PowerPoint OOXML supports only 4 embedded font variations per family name:

    1. regular
    2. bold
    3. italic
    4. boldItalic

    Warning: Any secondary bold weights (e.g., weights 700 and 900) will overwrite an existing slot unless they are assigned distinct font-family aliases.

    DrawingML Sequence Contract

    When injecting elements into <a:pPr>, they must follow this strict schema order to prevent OpenXML corruption:

    1. lnSpc
    2. spcBef
    3. spcAft
    4. buClr
    5. defRPr
  9. Apply a global design engine to slide generation

    master

    When using AI to generate slides for dom-to-pptx, include these design principles in your prompt to ensure high-quality, modern results:

    • Aesthetics: Aim for a clean, modern "Apple Keynote" style using multi-layered shadows, subtle gradients, and large rounded corners (32px).
    • Typography: Use dramatic contrast (e.g., massive, ultra-thin headers paired with bold, wide-tracked subheaders).
    • Layout: Prioritize whitespace (60%+) and implement advanced layouts like Bento-Box, Asymmetrical Editorial, or Typographic Poster.
    • Anti-Overflow: Ensure every container has overflow: hidden and min-height: 0. Limit body text to 12-15 words maximum.
    • Images: Use high-quality images from Pexels, Unsplash, or web URLs, styled with object-fit: cover and 32px border-radius.
  10. Design transitions based on presentation tone

    master

    When building presentations, align your transition choices with the intended audience and genre:

    Executive / Professional Decks

    Target: Board meetings, academic talks, sales reports.

    • Transitions: Use subtle, classic changes like slide-transition-fade or slide-transition-push (using transition-dir-l or transition-dir-r).
    • Speed: Use transition-duration-fast or transition-duration-normal to avoid distracting the audience.

    Creative / Launch Decks

    Target: Product launches, creative design portfolios.

    • Transitions: Use expressive transitions like slide-transition-gallery, slide-transition-doors, slide-transition-wind-left, or slide-transition-curtains (ideal for intro slides).
    • Speed: Use transition-duration-slow or custom durations (e.g., transition-dur-2000) for dramatic impact.
  11. Use Motion Design and Staging Rules

    master

    Animations must be coordinated to avoid "floating orphans" (static elements appearing while others animate).

    The Complete Staging Rule

    If a slide uses entry animations, every foreground element (titles, subtitles, body text, cards, images, lists) must be part of the entry sequence. Use sequential or staggered triggers:

    • Sequential: animate-trigger-on-click (Title) $\rightarrow$ animate-trigger-after (Subtitle) $\rightarrow$ Body text.
    • Staggered: Use animate-trigger-with combined with animate-delay-[ms] to build elements in parallel.

    Tone-Matching Matrix

    Genre / MoodApproved TransitionsApproved AnimationsBest Practices
    Executive / Corporateslide-transition-fade, slide-transition-push (with transition-dir-l / transition-dir-u)fade-in, fly-in (with to-up or to-right)Standard durations (700ms to 1000ms).
    Creative / Editorialslide-transition-gallery, slide-transition-wind-left, slide-transition-flip, slide-transition-doorszoom-in, bounce-in, wipe-in, Letter/Paragraph buildsUse dramatic entries and custom delays.
    Tech Launch / Product Demoslide-transition-split, slide-transition-push, slide-transition-checkersplit-in, fly-in, random-bars-in, wheelFocus on grid-wise reveals.
  12. Understand the layout and positioning system

    master
    The library does not interpret Flexbox or CSS Grid definitions. Instead, it measures the final computed x, y, width, height of every element relative to the slide root and places them using absolute positioning. This approach ensures that the exported PowerPoint matches the visual layout of the DOM exactly, regardless of the CSS layout method used.