# Document Editor overview

> A paginated, Word-style rich text editor for the browser with DOCX import and export, track changes, threaded comments, tables, images, mail merge and a document compare.

Birch UI Document Editor is a Word-style editor that runs entirely in the browser. Users write on real pages with margins, headers, footers and page numbers, format text with paragraph styles, build tables, drop in pictures, suggest changes and discuss them in comment threads. Your code opens and saves `.docx` files without a server, fills templates with customer data and compares two versions of a contract into a redline.

It runs on its own editing core, with a schema designed around Word's document model, and it follows the shared Birch UI widget contract, so it works in any framework.

> **Document Editor: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Birch UI Document Editor is a commercial product: $599 per developer, a one-time purchase with free updates forever, unlimited apps and unlimited end users. Without a license key every feature works and a small watermark is shown; on `localhost` the watermark is skipped while you develop.

## What it does

- **Rich text**: paragraph styles (Normal, Title, Subtitle, Heading 1 to 6, Quote, Code), bold, italic, underline, strikethrough, superscript, subscript, fonts, sizes, colours, highlight, alignment, line and paragraph spacing, indents, multi-level lists, links, symbols, clear formatting and a format painter. See [Editing](https://docs.birchui.com/document/editing.md).
- **Tables and pictures**: insert, merge and split cells, header rows, shading, borders and column resizing; pictures from a file, the clipboard or drag and drop, with resizing and alt text. See [Tables and images](https://docs.birchui.com/document/tables-and-images.md).
- **Page layout**: A3, A4, A5, Letter, Legal and Executive pages in portrait or landscape, margins, a ruler, zoom, headers and footers with "Page X of Y", and a web layout. Paragraphs and tables split across pages. See [Page layout](https://docs.birchui.com/document/page-layout.md).
- **Review**: track changes with authors and dates, accept and reject, a document compare that produces a redline, and an API for proposing edits from other tools. See [Track changes](https://docs.birchui.com/document/track-changes.md).
- **Comments**: anchored threads with replies and resolve. See [Comments](https://docs.birchui.com/document/comments.md).
- **References and forms**: footnotes and endnotes, bookmarks, cross-references, captions, tables of contents and figures, content controls with a form mode, and editing restrictions. See [Footnotes and references](https://docs.birchui.com/document/footnotes-and-references.md) and [Content controls and forms](https://docs.birchui.com/document/forms.md).
- **Files**: DOCX import and export written from scratch for this product, Markdown, HTML, RTF and OpenDocument converters, printing, and a vector PDF export. See [DOCX import and export](https://docs.birchui.com/document/docx.md), [Other formats](https://docs.birchui.com/document/formats.md) and [PDF export and print](https://docs.birchui.com/document/pdf-and-print.md).
- **Collaboration and versions**: a provider interface for real-time editing with presence, named versions and compare. See [Collaboration](https://docs.birchui.com/document/collaboration.md) and [Compare and version history](https://docs.birchui.com/document/compare-and-versions.md).
- **Templates**: merge fields and `{{customer.name}}` tokens with conditions, repeating sections and repeating table rows. See [Mail merge](https://docs.birchui.com/document/mail-merge.md).
- **Accessibility**: the ribbon follows the WAI-ARIA tabs and toolbar patterns, every command has a keyboard route, changes are announced, and right-to-left text works. See [Keyboard and accessibility](https://docs.birchui.com/document/keyboard.md) and what was tested in [Accessibility](https://docs.birchui.com/document/accessibility.md).

Before you commit to the editor, read [Limitations](https://docs.birchui.com/document/limitations.md); measured figures for long documents are in [Performance](https://docs.birchui.com/document/performance.md).

## Install

```bash
npm install @birchui/document
```

The package depends only on `@birchui/core` and `@birchui/license`, which npm installs for you. The editing core is part of the package; see [Editing engine](https://docs.birchui.com/document/editing-engine.md). Styles are injected the first time an editor is created. To ship the CSS yourself, pass `injectStyles: false` and import it:

```ts
import '@birchui/document/styles.css';
```

## Create an editor

`createDocumentEditor(container, options)` renders into an element you own and returns the editor API. Give the container a height; the editor fills it.

```ts title="engagement-letter.ts"
import { createDocumentEditor } from '@birchui/document';

const editor = createDocumentEditor(document.getElementById('letter')!, {
  licenseKey: 'LQ1.…',
  author: 'Priya Raman',
  page: { size: 'Letter', margins: { top: 72, right: 72, bottom: 72, left: 72 } },
  mergeFields: [
    { name: 'client.name', label: 'Client name' },
    { name: 'matter.reference', label: 'Matter reference' },
  ],
  content: {
    header: { type: 'doc', content: [{ type: 'paragraph', attrs: { align: 'right' }, content: [{ type: 'text', text: 'Harper & Lowe LLP' }] }] },
    content: {
      type: 'doc',
      content: [
        { type: 'paragraph', attrs: { styleId: 'Title' }, content: [{ type: 'text', text: 'Engagement letter' }] },
        { type: 'paragraph', content: [{ type: 'text', text: 'Dear {{client.name}},' }] },
      ],
    },
  },
});

editor.on('contentChange', ({ wordCount }) => console.info(`${wordCount} words`));
```

All measurements in the document model are in points (1/72 inch), as in Word. Picture and column widths are in CSS pixels.

## Save and load

`getJSON()` returns a plain, serialisable `DocumentData` object with the content, page setup, headers and footers, comment threads and document properties. Store it in your database and pass it back to `setJSON()` or the `content` option.

```ts
await fetch('/api/letters/481', { method: 'PUT', body: JSON.stringify(editor.getJSON()) });

editor.setJSON(await (await fetch('/api/letters/481')).json());
```

For Word files, use `importDocx(file)` and `exportDocx()`; see [DOCX import and export](https://docs.birchui.com/document/docx.md).

## Use it in your framework

The editor exports `documentEditorDefinition` (name `BirchDocumentEditor`, tag `birchui-document-editor`), which every Birch UI adapter wraps in its `/document` entry point, for example `BirchDocumentEditor` from `@birchui/react/document`; see [Frameworks](https://docs.birchui.com/document/frameworks.md). You can also call `createDocumentEditor` in a mount hook and `destroy()` in the matching unmount hook:

```tsx title="LetterEditor.tsx"
import { useEffect, useRef } from 'react';
import { createDocumentEditor, type DocumentData } from '@birchui/document';

export function LetterEditor({ value, onSave }: { value: DocumentData; onSave(data: DocumentData): void }) {
  const host = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const editor = createDocumentEditor(host.current!, { content: value, author: 'Priya Raman' });
    const off = editor.on('contentChange', () => onSave(editor.getJSON()));
    return () => {
      off();
      editor.destroy();
    };
  }, []);
  return <div ref={host} style={{ height: 720 }} />;
}
```

## Server-side and headless use

The DOCX reader and writer, the format converters, the PDF writer, mail merge, compare and pagination maths do not touch the DOM, so they also run in Node.js, workers and edge functions. Import them from `@birchui/document/headless`, which never loads the editor:

```ts title="generate-letter.mjs"
import { docxToDocument, documentToDocx, mergeDocument } from '@birchui/document/headless';
import { readFile, writeFile } from 'node:fs/promises';

const template = await docxToDocument(await readFile('engagement-letter.docx'));
const letter = mergeDocument(template, { client: { name: 'Northwind Traders Ltd' }, matter: { reference: 'NW-2026-118' } });
await writeFile('northwind-engagement.docx', await documentToDocx(letter));
```

Importing the package never touches `window` or `document`, so it is safe to import during server-side rendering. The other entry points (`/docx`, `/formats`, `/pdf`, `/collab`) are listed in the [API reference](https://docs.birchui.com/document/api.md#entry-points), and [Recipes](https://docs.birchui.com/document/recipes.md) has a complete server-side mail merge with throughput figures.
