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/officetohtmlPDF.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.
{ 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 responseOne-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 instanceWith 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)
| Option | Default | Description |
|---|---|---|
theme | "auto" | "light", "dark" or "auto" (follows the operating system). |
locale | page / browser | UI 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). |
height | container | Viewer height, e.g. 600 or "80vh". If the container has no height, 600px is used. |
toolbar | true | false hides it, or an object: { open, fileName, zoom, pages, search, print, download, fullscreen, theme, tools } (each true by default). |
statusbar | true | Status bar (page count, word count, sheet tabs, file size). |
formats | all | Allowed kinds: ["pdf","docx","pptx","sheet","image","text"]. |
maxFileSize | 200 MB | Largest file accepted, in bytes (0 = unlimited). |
fetchOptions | – | fetch() options for URL sources: headers, credentials, mode … |
allowedProtocols | http, https, blob, data | URL protocols accepted by load(). |
dropFiles | true | Open files dropped on the viewer. |
keyboard | true | Keyboard shortcuts while the viewer has focus. |
injectStyles | true | Inject 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: { … }
| Option | Default | Description |
|---|---|---|
assetsBase | jsDelivr (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. |
viewerCss | from assetsBase | URL of pdf_viewer.css, or false if you include it yourself. |
zoom | "auto" | Factor (1 = 100%) or "auto" | "page-fit" | "page-width" | "page-actual". |
page | 1 | Page to open. |
textLayer | true | Selectable text. false renders faster. |
annotations | true | Links and form fields. |
sidebar | false | Open the thumbnails/outline sidebar. |
pinchZoom | true | Two-finger zoom on touch screens. |
swipeNavigation | true | In presentation (full screen) mode: swipe or tap left/right to change pages. |
maxCanvasPixels | PDF.js default | Limit canvas size on low-memory devices. |
documentOptions | – | Extra getDocument() parameters (e.g. { password }). |
Word – docx: { … }
| Option | Default | Description |
|---|---|---|
pageView | true | Paper-like page. false = continuous flow. |
zoom | 1 / fit width | Initial zoom; on narrow screens the page is fitted to the width. |
rtl | "auto" | Detect direction per paragraph, or force true/false. |
imageSizes | true | Show images at the size used in the document. |
styleMap, includeEmbeddedStyleMap, includeDefaultStyleMap, ignoreEmptyParagraphs, convertImage | mammoth defaults | Passed to mammoth.js. |
allowInlineStyles | false | Keep style attributes produced by a custom style map. |
onMessages | – | Receives mammoth's conversion warnings. |
PowerPoint – pptx: { … }
| Option | Default | Description |
|---|---|---|
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: { … }
| Option | Default | Description |
|---|---|---|
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. |
readOnly | true | Allow editing cells (changes are not saved to the file). |
formulaBar | true | Cell address and value/formula of the selection. |
rowHeaders, colHeaders | true | Row numbers and column letters. |
columnSorting, contextMenu | false | Handsontable features. |
fixedRowsTop, fixedColumnsStart | 0 | Frozen rows/columns. |
activeSheet | workbook's | Index or name of the sheet to open. |
skipHiddenSheets | true | Hide sheets that are hidden in the workbook. |
maxRows | 5000 | Row limit of the "table" engine. |
language | – | Handsontable language code (register the language first). |
handsontableSettings, readOptions | – | Extra Handsontable settings / XLSX.read options. |
licenseKey, or use engine: "table".Images – image: { … } and text – text: { … }
| Option | Default | Description |
|---|---|---|
image.zoom | "auto" | Fit large images, "page-actual" (100%) or a factor. |
image.maxZoom / zoomStep | 20 / 1.25 | Zoom limits. |
image.wheelZoom | true | Mouse wheel zooms (otherwise Ctrl + wheel). |
image.checkerboard, image.background | false | Transparency grid / stage colour. |
text.wrap, text.lineNumbers | true | Line wrapping and numbers. |
text.formatJson | true | Pretty-print JSON. |
text.maxLength | 5 000 000 | Characters shown. |
API
| Member | Description |
|---|---|
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), zoom | Zoom (factor or preset). |
goToPage(n), nextPage(), previousPage(), page, pageCount | Pages, 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?), isFullscreen | Full screen (PDF and slides switch to presentation mode). |
setTheme(theme), theme, isDark | Theme. |
resize() | Re-measures after the container was resized while hidden. |
on(event, fn), once, off | Events; on returns an unsubscribe function. |
file, renderer, element | The 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
| Event | Payload |
|---|---|
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
| Keys | Action |
|---|---|
| Ctrl+F | Search |
| Ctrl+P | Print the document |
| Ctrl++ / - / 0, Ctrl + wheel | Zoom in / out / fit |
| PageUp / PageDown, Home / End | Previous / next page or slide, first / last |
| Ctrl+PageUp / PageDown | Previous / next sheet |
| Arrows, Space | Slides and PDF presentation mode: navigate; images: pan |
| R / Shift+R | Rotate (images, PDF) |
| Esc | Close search / exit full screen |
Security
- HTML converted from Word files is sanitised with DOMPurify;
javascript:and other unsafe links are removed and external links open withrel="noopener noreferrer". Element ids are prefixed so a document cannot override globals of your page. - Sheet names, cells, file names and text files are always inserted as text.
- PDF.js runs with
isEvalSupported: falseand without PDF scripting. - SVG images are displayed with
<img>, so scripts inside them never run. - URLs are limited to
http(s),blobanddata(allowedProtocols); files are limited to 200 MB (maxFileSize). - Printing uses a sandboxed iframe without script permission.
- Strict Content Security Policy: set
injectStyles: falseand link@meshesha/officetohtml/style.css, pass anonce, and self-host the libraries. PDF.js needsworker-src blob:or a same-origin worker.
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
- Remove all v1 includes (jQuery UI, pdf viewer files, jszip-utils, d3, nv.d3, reveal.js, verySimpleImageViewer, the v1 CSS) – one script replaces them.
- jQuery is optional.
$(el).officeToHtml({ url, inputObjId, pdfSetting, docxSetting, pptxSetting, sheetSetting })still works; settings are converted to v2 options. pdfSetting.setLang→locale; PDF toolbar flags →toolbar;disableTextLayer→pdf.textLayer: false.docxSetting.isRtl→docx.rtl;pptxSetting.slideMode→pptx.mode: "slideshow";sheetSetting.jqueryuiis gone (sheet tabs are built in).- The PDF viewer no longer needs a
localefolder or a fixed folder structure.
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).