接入应用

Render PPTX, DOCX and XLSX files to selectable HTML in a browser or Electron renderer. The ESM package includes TypeScript declarations and has zero required runtime dependencies. It uses native browser decompression and DOM layout. The Vue entry point has an optional peer dependency.

This checkout is version 0.1.4. Applications can inspect preview warnings, cancel loading and release an instance with destroy(). See the format limits below when deciding which documents to preview.

Installation

Install this release from the published archive.

npm install https://office-lite.changyo.me/download/office-lite-0.1.4.tgz

For the Vue 3 component, also install Vue in the consuming project with npm install vue@3.

The package has no other dependencies. vue is an optional peer and is only required if you import office-lite/vue.


Quick start

Automatic format detection

import { renderOffice } from "office-lite";

const container = document.getElementById("preview");
const response = await fetch("/files/report.docx");
const buffer = await response.arrayBuffer();

const instance = await renderOffice(container, buffer);

console.log(instance.warnings); // degradations, truncation, missing assets
// ...
instance.destroy(); // required before re-rendering into the same container

renderOffice identifies the format from [Content_Types].xml inside the package, not from the file name or extension. A renamed file is still rendered correctly; a non-OOXML archive is rejected with a clear error.

Per-format entry points

Use a format-specific entry point when the file type is already known. Word and Excel load the shared DrawingML renderer on demand for supported shapes.

import { renderPptx } from "office-lite/pptx";
import { renderDocx } from "office-lite/docx";
import { renderXlsx } from "office-lite/xlsx";

const deck = await renderPptx(container, buffer, {
  pages: { from: 1, to: 10 }, // 1-based, inclusive
});
console.log(deck.slideCount);

const doc = await renderDocx(container, buffer);
console.log(doc.pageCount);

const sheet = await renderXlsx(container, buffer, { sheet: 0 });
console.log(sheet.sheetNames);
await sheet.setSheet(1); // lazy parse + render the next worksheet

Input types

All three engines and renderOffice accept the same four input shapes:

Input Notes
ArrayBuffer Zero-copy; the common case when you already fetched the file.
Blob / File Read with arrayBuffer(). Drag-and-drop input arrives like this.
TypedArray (Uint8Array, Node Buffer, …) Only the view's byte range is used.
URL string Fetched with the global fetch; a non-2xx response rejects with the status code.

Both Blob and ArrayBuffer are recognised across realms (iframe, Web Worker, Node), so buffers produced elsewhere are not rejected. If an engine is given anything else, it throws 不支持的输入类型 and names the value it received.

Cancellation

Every engine accepts an AbortSignal. Cancellation is checked at each asynchronous boundary; blob URLs created before the abort are revoked and the promise rejects with an AbortError.

const controller = new AbortController();

const pending = renderOffice(container, buffer, {
  signal: controller.signal,
});

// e.g. the user selected another file
controller.abort();

Vue 3

<script setup>
import { ref } from "vue";
import OfficeLite from "office-lite/vue";

const file = ref(null); // ArrayBuffer or Blob
</script>

<template>
  <OfficeLite
    :src="file"
    @rendered="(instance) => console.log(instance.warnings)"
    @error="(error) => console.error(error)"
  />
</template>

The component owns the full lifecycle: when src changes, the previous render is aborted, the previous instance is destroyed, and late results are discarded. It exposes the active instance and a manual render() through a template ref.


API

All renderers accept an HTMLElement container and any of the input shapes listed above. They resolve to an instance object with a consistent contract.

renderOffice(container, src, opts?)

Option Type Description
signal AbortSignal Cancel the render.

The dispatcher also accepts the PPTX slide range and the XLSX options documented below.

Resolves to a format-specific instance: slideCount for PPTX, pageCount for DOCX, sheetNames and setSheet() for XLSX. All instances expose warnings and destroy().

detectKind(src)

Reads [Content_Types].xml and resolves to { kind, zip }, where kind is "pptx", "docx", "xlsx", or null. Useful when the application needs to choose a UI before rendering.

renderPptx(container, src, opts?)

Option Type Description
pages { from?: number, to?: number } Render a 1-based slide range. Page numbers follow the presentation.xml order.
signal AbortSignal Cancel the render.

Instance fields: slideCount, warnings, destroy().

The container width controls scaling. The renderer preserves the slide aspect ratio and re-lays out text at the resulting size.

renderDocx(container, src, opts?)

Option Type Description
signal AbortSignal Cancel the render.

Instance fields: pageCount, warnings, destroy().

Pages are split at explicit page breaks and section boundaries, with automatic pagination inside each section based on the configured page height.

renderXlsx(container, src, opts?)

Option Type Description
sheet number Initial worksheet index, zero-based.
layout "grid" or "print" Interactive worksheet grid (default) or the selected sheet split into paper pages.
paperSize "letter", "legal", "a4" or "a3" Override the workbook paper size in print layout to match the reference printer.
signal AbortSignal Cancel the render.

PowerPoint chart frames and worksheet charts with one-cell or two-cell anchors can display clustered columns, lines and areas from their saved series values. External workbooks are never opened to populate a chart. Combination, stacked, logarithmic and 3-D charts require additional support.

The instance exposes sheetNames, sheetIndex, setSheet(index), warnings and destroy(). In paper mode, read printPageCount and call setPrintPage(number) to display a one-based page.

Worksheets are parsed lazily. Only the active sheet pays the parse and DOM cost.

Vended helpers

office-lite/pptx exports openZip and parsePackage for applications that need to inspect a presentation or reuse a decompressed package. openZip returns a path-based handle with exists(), sizeOf(), text(), and blobURL().

office-lite/xlsx exports the number-format engine used by the grid:

import { formatCell, formatCodeOf, serialToDate } from "office-lite/xlsx";

formatCell(0.2568, "0.00%"); // "25.68%"
formatCell(45000, "yyyy/m/d"); // depends on the 1900 date system
formatCodeOf(4); // "#,##0.00"
serialToDate(45000, false); // Date

Low-level parsers (parseSheet, parseSharedStrings, parseStyles, parseNumbering, parseRels, parseTheme) are exported as well. They return internal models that may change between minor versions; the stable surface is the render functions and the helpers above.


Rendering model

The pipeline deliberately avoids layout shortcuts that would diverge from Office:

  1. Read the OPC package. Central-directory parsing, Zip64 support, CRC verification, and bounded decompression.
  2. Parse OOXML with local-name matching. Namespace prefixes vary between producers; element names do not.
  3. Resolve inheritance chains. Themes, slide masters and layouts, DOCX style chains (basedOn), and workbook styles.
  4. Lay out with browser text metrics. Text is measured in the target container so CJK/Latin spacing, hanging punctuation, bullets, and tab stops follow real font metrics.
  5. Calibrate against Office. Spacing, line height, autofit, table geometry, and pagination were tuned against PDF exports from Microsoft PowerPoint, Word, and Excel.

The result is responsive HTML/DOM, not a PDF clone. Where Office uses embedded fonts or platform-specific font substitution, output can differ; see Known limitations.


Format support

Capability PPTX DOCX XLSX
Theme colors, color maps, tint/shade Yes Yes Yes
Theme fonts and font schemes Yes Yes Yes
Text runs: size, weight, italic, underline, strike, color, spacing Yes Yes Yes
Paragraph alignment, indentation, line spacing Yes Yes —
Bullets and automatic numbering Yes Yes (multi-level) —
Tables Yes (cell fills, borders, merges) Yes (style chain, borders, merges) —
DrawingML auto shapes Yes (custom geometry approximated as rectangles) Inline shapes and supported column/paragraph anchors One-cell and two-cell anchors
Pictures Crop, luminance, duotone and fixed opacity Inline and anchored One-cell and two-cell anchors
Text boxes (DrawingML, VML, mc:AlternateContent) Yes Yes —
Content controls (SDT) — Yes —
Headers and footers — Yes —
Hyperlinks — Yes (protocol allowlist) Yes (protocol allowlist)
OMML math Linearized text — —
Merged cells — — Yes
Number formats — — Built-in and custom formats via SheetJS SSF
Conditional formatting — — Partial (cellIs, containsText, and related rules)
Sheet tabs and lazy switching — — Yes
Screen-style gridlines and headers — — Yes
Worksheet print layout — — Orientation, margins, scale, fit settings, page order and a single rectangular print area
SmartArt Saved drawing, Basic Cycle, or node text Not rendered Not rendered
2-D column, line and area charts Saved series values Unsupported Saved series values
Embedded audio and video Unsupported Unsupported Unsupported

Compatibility

Files

Browsers and Electron

Rendering requires a browser DOM, CSS layout and DecompressionStream("deflate-raw"). This checkout was exercised on Windows 11 with Chrome 158 and Electron 44.10.1. The Electron check opens and destroys one preview of each format in a sandboxed renderer with context isolation enabled. A file input can supply the File directly.

Node.js

The renderer targets a DOM. It runs under jsdom (used by the test suite), but jsdom does not implement full CSS layout, so geometry and text wrapping there are approximations. For pixel-accurate output, render in a real browser.


Input handling

The ZIP reader verifies CRCs and applies decompression limits. The parsers cap selected dimensions, nesting and preview sizes. Files can yield warnings, a partial preview, or an error. Use destroy() to release a preview and its resources.

Performance

The fixed suite contains 20 Word documents, 24 PowerPoint decks and 20 Excel workbooks. The current API-return benchmark recorded 18/20, 23/24 and 19/20 wins respectively. The display-ready benchmark waits for fonts, images and two animation frames. On the same Word and PowerPoint files, office-lite finished first on 19/20 and 23/24 comparisons respectively. PowerPoint led on 22/24 using Vue Office alone. The per-format target is 95%. Methods and per-file results

Stability and visual coverage

The unit and regression suite passed 169 tests. A strict TypeScript consumer compiled. Electron 44.10.1 opened and closed a preview of all three formats in a sandboxed window. In the 2,892-file opening test on this release, 2,833 files returned previews and 59 were rejected, with zero crashes or timeouts. Of those previews, 446 had zero text.

The visual suite contains 64 files and 28,835 pages printed with Microsoft Office LTSC 2024. At 192 dpi, each page is scored by the fraction of pixels with an RGB channel difference above 40/255. The suite averages pages within each file, then gives each file equal weight. The mean differing area fell from 2.7801% to 2.7488%. The 177-page Word contract improved from 9.2157% to 9.0594%. Text placement, merged cells and worksheet geometry still differ visibly from Office. Visual results and replication instructions

Five targeted input-handling checks passed on this release. They cover Word and Excel script links, decompression limits, CRC mismatches and encrypted ZIP entries. The public benchmark reports the case names, counts and test environment. Measured results

Known limitations

All formats

PPTX

DOCX

XLSX


Package layout

Path Responsibility
index.js Format detection and renderOffice dispatch
zip.js OPC/ZIP reader: Zip64, CRC-32, DecompressionStream, bomb limits
xml.js Small DOM helpers with namespace-agnostic local-name access
theme.js Shared DrawingML theme palette
pptx/ Presentation parser, renderer, and entry point
docx/ Document parser, style engine, pagination, and renderer
xlsx/ Workbook parser, number-format engine, and grid renderer
vue.js Vue 3 component with abort and generation guards
*.d.ts Hand-maintained declarations for every public entry point

Development

npm run verify           # unit + regression suite, then strict type check
npm test                 # unit and regression suite only
npm run check:types      # compile a strict consumer of every subpath
npm run demo             # rebuild the single-page demo harness
node scripts/bench-browser.mjs # cross-library benchmarks (real Chrome)
node scripts/corpus-run.mjs     # end-to-end run over the local corpora

The Office comparison tool opens the visual mode in bench.html and captures individual page elements.

Releasing

cd src/office-lite
npm pack --dry-run       # verify package contents
npm publish --access public

Published versions are immutable. Bump the version before publishing again.

License

The project uses the MIT license. Excel number formatting bundles SheetJS SSF 0.11.2 with its Apache 2.0 license.