# Automation API

Source: https://mroffice.ai/en/developers/embed/automation

Drive the open document from your page: read and write Word, Excel, PowerPoint and PDF files, code files and handwriting documents while the person works in them. Every call is promise-based, typed (mroffice-embed ships its .d.ts) and checked in the editor against the session: a view-only session reads but never writes. A change goes through the editor's own commands, the ones its ribbon runs, so it is one more edit of the session's user: Undo takes it back, everyone in the document sees it at once, Track Changes records it, and it is saved with the file.

```js
const editor = MROffice.open({ container: "#editor", appId: APP_ID, token: fetchToken });
await editor.ready;

const caps = await editor.getCapabilities();   // { apiVersion: 1, kind: "docx", mode: "edit", methods: [...], exportFormats }

// Word
await editor.word.insertText("CONFIDENTIAL", { location: "start" });
const { count } = await editor.word.replaceText("ACME", "Acme Ltd.", { matchCase: true });
await editor.word.insertMarkdown("## Terms\n\n- Net 30\n- Late fee 2%", { location: { bookmark: "terms" } });
await editor.word.insertTable([["Item", "Price"], ["Pen", 2]], { header: true, location: "end" });
await editor.word.addComment("Is 30 days right?", { anchorText: "within 30 days" });
const blocks = await editor.word.getContent();   // [{ type: "paragraph", id, style, text } | { type: "table", id, rows }]

// The file, as a Blob
const { blob, name } = await editor.document.export("pdf");
await editor.document.save();                  // as requestSave()

try {
  await editor.word.insertText("x");
} catch (error) {
  // error.code: "embed_view_only", "embed_target_not_found", … ; error.hint, error.docs, error.details
}
```

### Methods

| Method | What it does |
| --- | --- |
| getCapabilities() | apiVersion, the file's kind, the session's mode, the methods it may call now, and the formats document.export writes. |
| document.getInfo() | key, name, kind, mode, version, partnerVersion, and dirty (edits on their way to MR Office). |
| document.export(format?) | The document as a file, { blob, name, mimeType, size }: docx, pdf, odt, rtf, html, md or txt for Word; xlsx, pdf, csv, ods or html for Excel; pptx, pdf or odp for PowerPoint; pdf for PDF. What is typed is stored first. Refused when ui.features.export is false. |
| document.save() | Saves to your file now, as requestSave() does; resolves with the saved file. |
| word.getText(), word.getContent() | The plain text; the body as paragraphs ({ type, id, style, level?, text }) and tables ({ type, id, rows }), with the block ids other calls take. |
| word.getSelection(), word.setSelection(target) | What is selected ({ text, isEmpty, blockId }); select the occurrence-th match of a text, a bookmark, a content control, a block, or { all: true }. |
| word.insertText / insertHtml / insertMarkdown(content, { location? }) | At the selection (replacing it), at "start" or "end", or at { bookmark }, { contentControl: { tag \| title } } or { blockId }, with position before, after or replace. HTML and Markdown are read as the editor's own paste reads them; what it has no place for (scripts, styles, event handlers) is dropped. A content control keeps its identity when its text is filled in. |
| word.replaceText(find, replace, { matchCase?, wholeWord? }) | Word's Replace All: every occurrence, its formatting kept, tracked when Track Changes is on; resolves with { count }. |
| word.insertTable(rows, { header?, location? }) | A table from rows of values (the first row a header row with header: true). |
| word.addComment(text, { anchorText?, occurrence? }) | A comment on the selection, or on the occurrence-th match of anchorText, by the session's user. |
| word.getTrackedChanges(), acceptTrackedChanges(index?), rejectTrackedChanges(index?), setTrackChanges(on) | Review > Track Changes: the changes (index, kind, author, date, text); accept or reject one by its index, or all; turn tracking on or off for everyone. |
| word.getProperties(), word.setProperties(properties) | File > Info > Properties: title, subject, author, company, category, keywords, abstract, publishDate, companyAddress, companyPhone, companyFax, companyEmail. Saved in the file's docProps. |
| word.getBookmarks(), word.getContentControls() | The bookmarks; the content controls with their tag, title, type, text and whether they are locked. |
| excel.getSheets(), excel.addSheet(name?), excel.getUsedRange(sheet?) | The sheets ({ id, name, index, active, hidden }); a new sheet after the last; the used range of a sheet (the open one by default). |
| excel.getRange(address), setValues(address, values, { asTyped? }), setFormulas(address, formulas) | A1 addresses ("B2:D9", "Sales!A1:C3", "'My sheet'!A:A"; the open sheet when none is named). getRange gives values (computed) and formulas (as typed) row by row. A write is Excel's Enter Values: "=…" is a formula, and "50%", "$1,000" or "2026-10-01" are read as Excel reads them typed (asTyped: false stores the text as given); it resolves with the range as written. |
| powerpoint.getSlides(), addSlide({ title?, body?, layout?, index? }), replaceText(find, replace), goToSlide(index) | The slides ({ index, id, title, text, hidden }); a new slide with its layout's title and body filled in (title-content by default); Replace All across the deck; show a slide. |
| pdf.search(text, { limit? }), pdf.goToPage(page) | The find bar's own search ({ page, snippet, index } per match); show a page. |
| pdf.addHighlight(text, { page?, occurrence?, style? }), pdf.addComment(text, { page? }) | The ribbon's Highlight (or underline, strikethrough, squiggly) over a match, saved as the PDF's own markup; a sticky note on a page (the page shown by default). |
| code.getText(), code.getSelection(), code.setSelection(from, to?) | A code file's text as the editor holds it ({ text, language, lineCount }; "\n" line endings, the file's own come back when it is saved); the selection ({ text, isEmpty, from, to }, each { line, column, offset }, 1-based); select from one { line, column? } to another. |
| code.setText(text), code.insertText(text, { location? }) | Replace the whole file; insert at the selection (replacing it), at "start" or "end", or at { line, column? }. Written as the person types: Undo takes it back. |
| ink.getStrokes(), ink.clear() | A handwriting document's pen, pencil and highlighter strokes ({ count, strokes: [{ index, tool, color, widthPt }] }); erase them all in one step (Undo brings them back). |

### Excel, PowerPoint and PDF

```js
// Excel (.xlsx)
const sheets = await editor.excel.getSheets();            // [{ id, name, index, active, hidden }]
await editor.excel.setValues("Sales!A1:B3", [["Region", "Q1"], ["North", 10], ["South", 30]]);
await editor.excel.setFormulas("Sales!B4", [["=SUM(B2:B3)"]]);
const range = await editor.excel.getRange("Sales!A1:B4");  // { address, values: [[…]], formulas: [[…]] }
await editor.excel.addSheet("Summary");
const used = await editor.excel.getUsedRange("Sales");      // { address: "Sales!A1:B4", rowCount, columnCount }

// PowerPoint (.pptx)
await editor.powerpoint.addSlide({ title: "Next steps", body: "Sign\nShip", index: 1 });
await editor.powerpoint.replaceText("2025", "2026");
const { slides } = await editor.powerpoint.getSlides();    // [{ index, id, title, text, hidden }]
await editor.powerpoint.goToSlide(0);

// PDF
const hits = await editor.pdf.search("indemnify");          // [{ page, snippet, index }]
await editor.pdf.addHighlight("indemnify", { page: hits[0].page });
await editor.pdf.addComment("Check this clause", { page: 3 });
await editor.pdf.goToPage(1);
```

### Places and rules

- Call after ready; a call made earlier waits for it. Calls run one after another, in the order you make them.
- Positions never cross the frame: a place is named by its text, a block id (from word.getContent), a bookmark, a content control's tag or title, an A1 address, a slide index or a page number.
- A writing method runs in an edit session only: in a view session it rejects with embed_view_only, in a comment, review or fillForms session with embed_mode_read_only. word.addComment and pdf.addComment also run in a comment or review session that may comment (else embed_comment_not_allowed); accepting or rejecting changes needs permissions.acceptRejectChanges; document.export needs permissions.download (embed_download_not_allowed) and a format permissions.export lists (embed_export_format_not_allowed). A method for another kind of file rejects with embed_command_unsupported; an unknown method or apiVersion with embed_command_unknown. Nothing reaches the document.
- Other errors: embed_command_invalid (error.details.fields names the parameter), embed_target_not_found, embed_command_not_applicable (error.details says why), embed_read_only (a protected or locked file, or one still being prepared), embed_editor_not_ready, embed_export_disabled, embed_command_failed. Each carries error.hint and error.docs (see Errors and debugging).
- Limits per call: 1 MB of text, HTML or Markdown; 100,000 cells per range; tables up to 500 rows of 63 cells.
- This is apiVersion 1. Within a version methods are only ever added, never changed: getCapabilities() says which this editor runs, and a page written for a newer editor can test for a method before it calls it.

### Without embed.js

If you build your own frame host, a call is one command message and its answer the commandResult with the same id (postMessage reference). The frame reads commands only from the origin that sent init.

```js
// Your own frame host: one "command" per call, answered by "commandResult" with the same id
frame.postMessage({ source: "mroffice-embed", version: 1, type: "command", id: "c1",
  payload: { method: "word.replaceText", params: { find: "ACME", replace: "Acme" }, apiVersion: 1 } }, EDITOR_ORIGIN);
// ← { source: "mroffice-embed", version: 1, type: "commandResult", id: "c1", payload: { ok: true, result: { count: 3 } } }
// ← { …, payload: { ok: false, error: { code: "embed_view_only", message: "…" } } }
```

### Compared with Office.js and ONLYOFFICE

The names follow Office.js's hosts: Word's body, paragraphs, tables and content controls, Excel's Range values and formulas, PowerPoint's slides. The set covers what ONLYOFFICE's Automation API connector offers for the same jobs (executeMethod PasteHtml, SearchAndReplace, AddComment, AcceptReviewChanges, GetAllContentControls), as promises that reject with an error code instead of callbacks; and unlike a macro run on its own, each call is an edit of the person in the editor, under their session's rights.
