> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Office.js in the browser

OfficeJS is the same in a page. Two things change: there is no file system, and you supply the fonts.

## Edit only

If you only edit and save, import from `@reductoai/docx/officejs`. It needs no fonts and no layout.

```ts theme={null}
import { WordDocument } from "@reductoai/docx/officejs";

const input = document.querySelector<HTMLInputElement>("input[type=file]")!;
const file = input.files![0];

const doc = await WordDocument.fromBytes(new Uint8Array(await file.arrayBuffer()));
doc.body.search("DRAFT").items.forEach((hit) => hit.insertText("FINAL", "Replace"));

const bytes = await doc.toBytes();
const blob = new Blob([bytes], {
  type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
```

## Edit, lay out and render

For `toPdf()`, `readPage()` and `updateFields()`, import from `@reductoai/docx/browser` and install a layout host once:

```ts theme={null}
import { WordDocument, browserLayoutHost, portableFaceProvider } from "@reductoai/docx/browser";

const fonts = portableFaceProvider((file) => `/fonts/${file}`);
browserLayoutHost({ fonts });

const doc = await WordDocument.fromBytes(bytes);
doc.body.insertParagraph("Approved.", "End");

const pdf = await doc.toPdf(); // Uint8Array
```

`browserLayoutHost` sets the default host for every `WordDocument` in the page. The host keeps one layout for each document and lays out again only after an edit.

### The layout engine

Layout runs in `@reductoai/docx/engine.wasm`, a file in the package. Vite, webpack and Next.js copy it into your build, so you set nothing. A page with an import map for `@reductoai/docx/engine.wasm` also needs nothing more. The engine draws EMF and WMF pictures itself.

With another bundler, or to serve the file from another place, give its URL once, before the first layout:

```ts theme={null}
import { setLayoutEngine } from "@reductoai/docx/browser";

setLayoutEngine("/engine.wasm"); // a copy of node_modules/@reductoai/docx/wasm/engine.wasm
```

To set it for one call, pass `engine`: `browserLayoutHost({ fonts, engine: "/engine.wasm" })`. `layoutDocxInBrowser` and `createBrowserEditorHost` take the same option.

When the file is not at the URL, layout throws `no layout engine` with the URL that failed.

**esbuild** does not copy the file. Load `.wasm` files as files and resolve the import against the bundle:

```ts theme={null}
// esbuild app.ts --bundle --format=esm --outdir=dist --loader:.wasm=file
import { setLayoutEngine } from "@reductoai/docx/browser";
import engineFile from "@reductoai/docx/engine.wasm";

setLayoutEngine(new URL(engineFile, import.meta.url).href);
```

In TypeScript, declare the import: `declare module "*.wasm" { const file: string; export default file; }`.

**Cloudflare Workers** import the file as a compiled module. Pass it to `setLayoutEngine(engine)`, and set `REDUCTO_API_KEY` as a secret with the `nodejs_compat` flag. Start the first layout inside a request that waits for its result: a Worker cannot finish a promise that an ended request started.

**Content-Security-Policy.** The page must allow WebAssembly: add `'wasm-unsafe-eval'` to `script-src`. Without it the engine does not start and the error names the directive.

**Engine failures.** If the engine fails while it opens or lays out a document (a WebAssembly trap, which Safari 18.0 sometimes hits), the call starts a fresh engine and tries once more, in the same Session. If that fails too, the call throws the first error. License and bad-file errors are not retried.

### Host options

`browserLayoutHost` takes the same options as `layoutDocxInBrowser`:

| Option | Default | Notes |
| - | - | - |
| `fonts` | required | A `FaceProvider`. See [Fonts](https://docs.reducto.ai/office/docx/getting-started/fonts.md) |
| `trackedChanges` | `"final"` | `"inline"` shows insertions and deletions in the text; `"balloons"` puts them in the margin |
| `comments` | `"hidden"` | `"balloons"` shows comments in a margin |
| `onProgress` | none | Progress events; `progressText(event)` formats one |

## Run it in a Web Worker

Layout of a long document takes time. Put OfficeJS in a worker so the page stays responsive:

```ts theme={null}
// docx.worker.ts
import { WordDocument, browserLayoutHost, portableFaceProvider } from "@reductoai/docx/browser";

browserLayoutHost({ fonts: portableFaceProvider((file) => `/fonts/${file}`) });

self.onmessage = async (event: MessageEvent<{ bytes: Uint8Array }>) => {
  const doc = await WordDocument.fromBytes(event.data.bytes);
  doc.body.insertParagraph("Generated in a worker.", "End");
  const docx = await doc.toBytes();
  const pdf = await doc.toPdf();
  self.postMessage({ docx, pdf }, [docx.buffer, pdf.buffer]);
};
```

```ts theme={null}
// page
const worker = new Worker(new URL("./docx.worker.ts", import.meta.url), { type: "module" });
```

The worker must be a **module** worker (`type: "module"`).

## Differences from Node

| | Node | Browser |
| - | - | - |
| Open and save | `open(path)`, `save(path)` | `fromBytes(bytes)`, `toBytes()` |
| Fonts | System fonts or portable profile, automatic | A `FaceProvider` you pass |
| PDF | `toPdf(path?)` | `toPdf()` |
| PNG | `toPng()` | Paint the layout to a canvas. See [PNG](https://docs.reducto.ai/office/docx/conversion/png.md) |
| Layout host | Installed on import | `browserLayoutHost({ fonts })` |
