Documentation

OfficeToHtml v2 shows Word, PowerPoint, spreadsheet, PDF, image and text files in the browser with one Office-like viewer. Everything happens on the client: files are never uploaded anywhere.

Installation

With a bundler (Vite, webpack, Angular CLI, Next.js …)

npm install @meshesha/officetohtml

PDF.js, mammoth.js, SheetJS, Handsontable and PPTXjs are installed as dependencies but only downloaded by the browser when a file of that type is opened (your bundler puts each one in its own chunk).

With a <script> tag

<div id="viewer" style="height:600px"></div>
<script src="https://cdn.jsdelivr.net/npm/@meshesha/officetohtml@2/dist/officetohtml.umd.js"></script>
<script>
  const viewer = new OfficeToHtml.OfficeViewer("#viewer");
  viewer.load("files/report.docx");
</script>

The browser bundle (window.OfficeToHtml) contains the viewer only. The format libraries are loaded on demand from version-pinned CDN URLs, or from your own server – see Libraries & self-hosting. It also registers the <office-viewer> element and, if jQuery is on the page, $.fn.officeToHtml.

Quick start

import { OfficeViewer } from "@meshesha/officetohtml";

const viewer = new OfficeViewer("#viewer", {
  theme: "auto",          // "light" | "dark" | "auto"
  locale: "en",           // UI language
});

// A URL, File, Blob, ArrayBuffer or Uint8Array:
await viewer.load("/files/budget.xlsx");

// Files from an <input type="file">:
viewer.bindInput("#file-input");

// Or let the user pick / drop a file (both are built in):
viewer.open();

The viewer fills its container. Give the container a height (for example height: 600px or 80vh), or pass the height option.

The file type is detected from the content (magic bytes and ZIP structure), so files without an extension or with a wrong one work too. Pass { fileName } or { type: "xlsx" } to load() to override.

Loading protected files (custom headers)

const viewer = new OfficeViewer("#viewer", {
  fetchOptions: { headers: { Authorization: `Bearer ${token}` }, credentials: "include" },
});
await viewer.load("/api/documents/42");   // name and type come from the response

One-liner

import { renderOffice } from "@meshesha/officetohtml";
const viewer = await renderOffice("#viewer", file, { theme: "dark" });

Frameworks

React

import { useRef } from "react";
import { OfficeViewer } from "@meshesha/officetohtml/react";

export function Preview({ file }) {
  const ref = useRef(null);  // ref.current is the OfficeViewer instance
  return (
    <OfficeViewer
      ref={ref}
      src={file}                       // URL, File, Blob or ArrayBuffer
      options={{ theme: "auto" }}      // read on mount
      style={{ height: 600 }}
      onLoad={({ file }) => console.log(file.kind)}
      onError={(error) => console.error(error.code)}
      onPageChange={(page, total) => {}}
    />
  );
}

The component is client-only (it uses the DOM). In Next.js use it in a "use client" component.

Vue 3

<script setup>
import { ref } from "vue";
import { OfficeViewer } from "@meshesha/officetohtml/vue";
const src = ref("/files/slides.pptx");
const viewerRef = ref();   // viewerRef.value.viewer is the instance
</script>

<template>
  <OfficeViewer ref="viewerRef" :src="src" :options="{ pptx: { mode: 'slideshow' } }"
                style="height:600px" @load="onLoad" @error="onError" />
</template>

Or register it globally: app.use(OfficeToHtmlPlugin).

Angular

Angular supports custom elements natively, so the Angular entry point registers <office-viewer>:

// main.ts
import { defineOfficeViewerElement } from "@meshesha/officetohtml/angular";
defineOfficeViewerElement();

// preview.component.ts
import { Component, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";

@Component({
  selector: "app-preview",
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `<office-viewer [attr.src]="url" theme="auto" style="height:600px"
                            (office-load)="loaded($event)"></office-viewer>`,
})
export class PreviewComponent {
  url = "/assets/report.docx";
  loaded(e: Event) { console.log((e as CustomEvent).detail.file); }
}

A ready-to-copy standalone component that wraps the OfficeViewer class directly is in examples/angular.

jQuery

The v1 plugin API still works – existing pages only need the new script:

// v1 style
$("#resolte-contaniner").officeToHtml({ url: "files/demo.docx" });
$("#resolte-contaniner").officeToHtml({ inputObjId: "select_file" });

// v2 style – all options of the OfficeViewer class
$("#viewer").officeViewer({ src: "files/demo.pdf", theme: "dark" });
const viewer = $("#viewer").officeViewer();   // the instance

With a bundler: import { installJQueryPlugin } from "@meshesha/officetohtml/jquery"; installJQueryPlugin($);

Web Component

<office-viewer src="files/demo.pdf" theme="auto" locale="en" style="height:600px"></office-viewer>

<script type="module">
  import { defineOfficeViewerElement } from "@meshesha/officetohtml/element";
  defineOfficeViewerElement();
  const el = document.querySelector("office-viewer");
  el.addEventListener("office-load", (e) => console.log(e.detail.file));
  el.options = { sheet: { engine: "table" } };  // full options
  el.source = someFile;                         // File / Blob / ArrayBuffer
</script>

Attributes: src, file-name, type, theme, locale, dir, height, toolbar="false", statusbar="false". Events: office-load, office-error, office-pagechange.

Options

All options are optional. new OfficeViewer(container, options)

OptionDefaultDescription
theme"auto""light", "dark" or "auto" (follows the operating system).
localepage / browserUI language: en he ar es fr de ru zh or one added with registerLocale(). Defaults to <html lang>, then the browser language.
messages–Override individual UI strings, e.g. { open: "Browse…" }.
dir"auto"UI direction: "ltr", "rtl" or "auto" (from the container's dir or the locale).
heightcontainerViewer height, e.g. 600 or "80vh". If the container has no height, 600px is used.
toolbartruefalse hides it, or an object: { open, fileName, zoom, pages, search, print, download, fullscreen, theme, tools } (each true by default).
statusbartrueStatus bar (page count, word count, sheet tabs, file size).
formatsallAllowed kinds: ["pdf","docx","pptx","sheet","image","text"].
maxFileSize200 MBLargest file accepted, in bytes (0 = unlimited).
fetchOptions–fetch() options for URL sources: headers, credentials, mode …
allowedProtocolshttp, https, blob, dataURL protocols accepted by load().
dropFilestrueOpen files dropped on the viewer.
keyboardtrueKeyboard shortcuts while the viewer has focus.
injectStylestrueInject the stylesheet. Set false and link officetohtml.css for a strict CSP.
nonce–CSP nonce for injected <style>, <link> and <script> elements.
libs–Where the format libraries come from – see Libraries.
renderers–Replace or add renderers – see Custom renderers.
pdf, docx, pptx, sheet, image, text–Per-format options (below).

PDF – pdf: { … }

OptionDefaultDescription
assetsBasejsDelivr (pinned)Base URL of the PDF.js worker, CMaps, fonts, wasm and viewer CSS (a copy of the pdfjs-dist folder).
workerSrc / workerPort–Use a specific worker URL or an existing Worker.
viewerCssfrom assetsBaseURL of pdf_viewer.css, or false if you include it yourself.
zoom"auto"Factor (1 = 100%) or "auto" | "page-fit" | "page-width" | "page-actual".
page1Page to open.
textLayertrueSelectable text. false renders faster.
annotationstrueLinks and form fields.
sidebarfalseOpen the thumbnails/outline sidebar.
pinchZoomtrueTwo-finger zoom on touch screens.
swipeNavigationtrueIn presentation (full screen) mode: swipe or tap left/right to change pages.
maxCanvasPixelsPDF.js defaultLimit canvas size on low-memory devices.
documentOptions–Extra getDocument() parameters (e.g. { password }).

Word – docx: { … }

OptionDefaultDescription
pageViewtruePaper-like page. false = continuous flow.
zoom1 / fit widthInitial zoom; on narrow screens the page is fitted to the width.
rtl"auto"Detect direction per paragraph, or force true/false.
imageSizestrueShow images at the size used in the document.
styleMap, includeEmbeddedStyleMap, includeDefaultStyleMap, ignoreEmptyParagraphs, convertImagemammoth defaultsPassed to mammoth.js.
allowInlineStylesfalseKeep style attributes produced by a custom style map.
onMessages–Receives mammoth's conversion warnings.

PowerPoint – pptx: { … }

OptionDefaultDescription
mode"list""list" (all slides) or "slideshow".
scale"fit""fit" (width), "contain" or a factor.
viewerOptions–Any PPTXjs v2 viewer option, e.g. { slideshow: { autoplay: 5, loop: true, transition: "slide" } }.

Spreadsheets – sheet: { … }

OptionDefaultDescription
engine"handsontable"Excel-like grid, or "table" – a light read-only table that needs no Handsontable.
licenseKey"non-commercial-and-evaluation"Your Handsontable license key.
readOnlytrueAllow editing cells (changes are not saved to the file).
formulaBartrueCell address and value/formula of the selection.
rowHeaders, colHeaderstrueRow numbers and column letters.
columnSorting, contextMenufalseHandsontable features.
fixedRowsTop, fixedColumnsStart0Frozen rows/columns.
activeSheetworkbook'sIndex or name of the sheet to open.
skipHiddenSheetstrueHide sheets that are hidden in the workbook.
maxRows5000Row limit of the "table" engine.
language–Handsontable language code (register the language first).
handsontableSettings, readOptions–Extra Handsontable settings / XLSX.read options.
Handsontable license: Handsontable is free for non-commercial use and evaluation only. For commercial products buy a license and pass licenseKey, or use engine: "table".

Images – image: { … } and text – text: { … }

OptionDefaultDescription
image.zoom"auto"Fit large images, "page-actual" (100%) or a factor.
image.maxZoom / zoomStep20 / 1.25Zoom limits.
image.wheelZoomtrueMouse wheel zooms (otherwise Ctrl + wheel).
image.checkerboard, image.backgroundfalseTransparency grid / stage colour.
text.wrap, text.lineNumberstrueLine wrapping and numbers.
text.formatJsontruePretty-print JSON.
text.maxLength5 000 000Characters shown.

API

MemberDescription
load(source, { fileName?, type?, signal? })Loads a URL, File, Blob, ArrayBuffer or typed array. Resolves with { file, renderer }; rejects with an OfficeError.
open()Opens the file picker.
bindInput(input)Loads files chosen in an <input type="file"> (element, id or selector). Returns an unsubscribe function.
close()Closes the document.
zoomIn(), zoomOut(), setZoom(z), zoomZoom (factor or preset).
goToPage(n), nextPage(), previousPage(), page, pageCountPages, slides or sheets (1-based).
search(text, { matchCase? })Finds and highlights text. Resolves with { total, current }.
print()Prints only the document.
download()Saves the original file.
getText()Plain text of the document.
toggleFullscreen(force?), isFullscreenFull screen (PDF and slides switch to presentation mode).
setTheme(theme), theme, isDarkTheme.
resize()Re-measures after the container was resized while hidden.
on(event, fn), once, offEvents; on returns an unsubscribe function.
file, renderer, elementThe open file (bytes, name, kind, ext, size …), the active renderer and the root element.
destroy()Removes the viewer, listeners and object URLs.
OfficeViewer.registerRenderer(kind, factory)Global renderer registration.

Other exports: renderOffice(), detectFormat(), readSource(), registerLocale(), sanitizeHtml(), printDocument(), OfficeError, VERSION, LIB_VERSIONS. Full TypeScript types are included.

Errors

OfficeError.code is one of: SOURCE_ERROR, INVALID_URL, FILE_TOO_LARGE, UNSUPPORTED_FORMAT, FORMAT_DISABLED, LIBRARY_LOAD_ERROR, PARSE_ERROR, PASSWORD_REQUIRED, ABORTED, DESTROYED.

Events

EventPayload
loadstart{ source }
progress{ phase: "download" | "render", loaded, total, ratio }
load{ file, renderer }
error{ error: OfficeError }
warning{ message, detail }
pagechange{ page, total }
zoomchange{ zoom }
themechange{ theme, dark }
fullscreenchange{ fullscreen }
destroy{}

Libraries & self-hosting

Each format library is resolved in this order: a module you pass in libs.modules, a global variable already on the page (pdfjsLib, mammoth, XLSX, Handsontable, PPTXjs), then the npm package (bundler builds) or libs.urls (script-tag build, defaulting to version-pinned CDN URLs).

// Script-tag build, all files served from your own server:
new OfficeToHtml.OfficeViewer("#viewer", {
  libs: {
    urls: {
      pdfjs:        "/vendor/pdfjs/build/pdf.min.mjs",
      pdfjsViewer:  "/vendor/pdfjs/web/pdf_viewer.mjs",
      mammoth:      "/vendor/mammoth/mammoth.browser.min.js",
      xlsx:         "/vendor/xlsx/xlsx.full.min.js",
      handsontable: "/vendor/handsontable/handsontable.full.min.js",
      pptxjs:       "/vendor/pptxjs/pptxjs.umd.js",
    },
  },
  pdf: { assetsBase: "/vendor/pdfjs/" },  // worker, cmaps, fonts, css
});

// Bundler build, explicit modules (e.g. to share instances):
import * as XLSX from "xlsx";
new OfficeViewer("#viewer", { libs: { modules: { xlsx: XLSX } } });

The files to copy are in node_modules: pdfjs-dist/{build,web,cmaps,standard_fonts,wasm,iccs}, mammoth/mammoth.browser.min.js, xlsx/dist/xlsx.full.min.js, handsontable/dist/handsontable.full.min.js, @meshesha/pptxjs/dist/pptxjs.umd.js. The repository's scripts/build-site.mjs does exactly that for this website.

With Vite you can point the PDF worker at the bundled file: import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url" → pdf: { workerSrc }.

Languages

Built in: English, Hebrew, Arabic, Spanish, French, German, Russian and Chinese (list). Hebrew and Arabic switch the whole UI to right-to-left. Add a language or change any text:

import { registerLocale } from "@meshesha/officetohtml";
registerLocale("it", { open: "Apri file", download: "Scarica", print: "Stampa" /* … */ });

new OfficeViewer("#viewer", { locale: "it", messages: { emptyHint: "Trascina qui un file" } });

Theming

The viewer uses CSS custom properties on .oth (and .oth[data-theme="dark"]):

.oth {
  --oth-accent: #0f766e;     /* buttons, focus, active states */
  --oth-bg: #f5f5f4;         /* page background */
  --oth-surface: #ffffff;    /* toolbar, panels */
  --oth-border: #e7e5e4;
  --oth-text: #1c1917;
  --oth-radius: 0;           /* square corners */
  --oth-font: "Inter", sans-serif;
}

Keyboard shortcuts

KeysAction
Ctrl+FSearch
Ctrl+PPrint the document
Ctrl++ / - / 0, Ctrl + wheelZoom in / out / fit
PageUp / PageDown, Home / EndPrevious / next page or slide, first / last
Ctrl+PageUp / PageDownPrevious / next sheet
Arrows, SpaceSlides and PDF presentation mode: navigate; images: pan
R / Shift+RRotate (images, PDF)
EscClose search / exit full screen

Security

Report vulnerabilities privately – see SECURITY.md.

Custom renderers

Renderers are small objects; optional methods enable the matching toolbar buttons automatically.

import { OfficeViewer } from "@meshesha/officetohtml";

OfficeViewer.registerRenderer("text", (ctx) => ({
  async render() {
    const html = myMarkdownToSafeHtml(new TextDecoder().decode(ctx.file.bytes));
    ctx.container.append(html);                 // a DOM node you built safely
    ctx.setStatus("Markdown");
  },
  destroy() {},
  // optional capabilities: getZoom/setZoom, getPage/setPage/getPageCount,
  // search/searchNext/searchPrevious/clearSearch, print, getText, onResize ...
}));

Migrating from v1

FAQ

Can it show .doc, .ppt or .odt files?

No. These binary/legacy formats have no reliable browser-side reader. The viewer explains that and offers a download. Convert them to .docx/.pptx (Word, PowerPoint or LibreOffice: soffice --headless --convert-to docx file.doc). Old .xls files are supported.

The Word document looks different from Word.

mammoth.js converts the document's structure (headings, lists, tables, images, links) into clean HTML; it intentionally ignores most visual formatting such as exact fonts, colours, spacing and page layout. Image sizes are restored by OfficeToHtml. Use docx.styleMap to map Word styles to your own CSS classes.

Files don't load from another domain.

The server must allow cross-origin requests (CORS). Alternatively fetch the file yourself and pass the Blob / ArrayBuffer to load().

Does it work with Django, Magento, RequireJS …?

Yes. v2 does not depend on a folder layout: the browser bundle is a single file, and library locations are configured with libs.urls and pdf.assetsBase. With RequireJS/AMD, load officetohtml.umd.js as an AMD module or before RequireJS.

Is my file uploaded anywhere?

No. Everything happens in the browser. Only the libraries themselves are downloaded (from your server or the CDN).