Write a .docx with the typed model, read it back
Write a Word document with formatting and a table, download it, and read it back.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/ooxml
Build a .docx from a title, paragraphs with bold and italic runs and a small
table (paragraph, run, fromText, tableFromRows), download it, read the
bytes back and show toText and the surviving run formatting.
Uses @awacloud/ooxml (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
When to use it
Producing a Word document from application data in the browser — a filled
form, a report, a letter — and checking what was written with the same
package instead of trusting the bytes. The typed model is the same one
read() returns, so a document can be read, changed and written again.
Copy-paste steps
npm install @awacloud/ooxml(it depends on@awacloud/fw).- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/andnode_modules/@awacloud/ooxml/src/at/vendor/ooxml/(any static server). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. Keep the legal notice under</main>: copy../../LICENSES/AGPL-3.0-only.txtalong, or point its link at your copy. - Build your own
bodyarray:paragraph(text, { rPr, pPr }),run(text, rPr),tableFromRows(rows),hyperlink(text, target, { rId }), or the lower-level typed nodes they return.
What it shows
- Wiring: one
ModuleRuntimewith@awacloud/ooxml'sfw_require(the zip and XML closure) andmodulesarrays plus fw'sdownload;rt.resolve('docx')is the typed API. The@awacloud/ooxml/docxsubpath is not served under/vendor/ooxml/, so a page takesdocxfrom the root. - The model:
{ type: 'document', body: [...] }where a paragraph holds runs, a run holds text and an optional flatrPrbag ({ bold: true },{ italic: true }, …), andtableFromRowsbuilds a table of one paragraph per cell.fromText(lines)is the one-paragraph-per-line shortcut. - Write:
docx.write(document)returns the bytes of an OPC zip container ([Content_Types].xml,word/document.xml, …). Two writes of the same model may differ in bytes (the zip writer stamps the time), so the test compares models and text, never bytes. - Read:
docx.read(bytes)returns{ document, package, hyperlinks, numbering, … };docx.toText(document)joins paragraphs with newlines and table cells with tabs. The test checks the paragraph order, the table cells and thatboldanditalicare back on the runs of the read model. - Not shown: images (
imageRun), hyperlinks and numbering (both need theiroptson write), styles, headers and footers, the coverage bundles (docxLargeBundle,docxFullBundle) and the 36 opt-in extras.
Code
main.js
// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { download } from '@awacloud/fw/dom/fs/download.js';
import { fw_require, modules } from '@awacloud/ooxml';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules, download]);
const DOCX = rt.resolve('docx');
const DOWNLOAD = rt.resolve('download');
const DOCX_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
/**
* A typed document: a bold title paragraph, a paragraph mixing plain, bold and
* italic runs (`rPr` is a flat bag of run properties), and a small table.
* @param {{ title?: string, rows?: string[][] }} [content]
*/
export function buildDocument({
title = 'Site visit', rows = [['Area', 'Status'], ['Pump', 'runs hot'], ['Valve', 'leaks']],
} = {}) {
return {
type: 'document',
body: [
DOCX.paragraph(title, { rPr: { bold: true } }),
{
type: 'paragraph',
children: [
DOCX.run('Measured on '), DOCX.run('site', { bold: true }), DOCX.run(', not '),
DOCX.run('assumed', { italic: true }), DOCX.run('.'),
],
},
...DOCX.fromText(['Findings follow.']).body,
DOCX.tableFromRows(rows),
],
};
}
/** The `.docx` bytes (an OPC zip container). @param {object} doc */
export const write = (doc) => DOCX.write(doc);
/**
* Read the bytes back: the plain text (paragraphs by line, table cells by tab)
* and the runs of the second paragraph with the formatting that survived.
* @param {Uint8Array} bytes
*/
export function readBack(bytes) {
const { document: doc } = DOCX.read(bytes); // `read` also returns the package, hyperlinks and numbering
const runs = doc.body[1].children.map((run) => ({
text: run.children.map((t) => t.value).join(''), bold: run.rPr?.bold === true, italic: run.rPr?.italic === true,
}));
return { text: DOCX.toText(doc), runs, paragraphs: doc.body.filter((b) => b.type === 'paragraph').length };
}
const text = /** @type {HTMLElement} */ (document.getElementById('text'));
const runList = /** @type {HTMLElement} */ (document.getElementById('runs'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
const saveButton = /** @type {HTMLButtonElement} */ (document.getElementById('download'));
let bytes = /** @type {Uint8Array | null} */ (null);
document.getElementById('build')?.addEventListener('click', () => {
bytes = write(buildDocument());
const back = readBack(bytes);
text.textContent = back.text;
runList.replaceChildren(...back.runs.map((run) => {
const li = document.createElement('li');
const style = [run.bold && 'bold', run.italic && 'italic'].filter(Boolean).join(', ');
li.textContent = style ? `${JSON.stringify(run.text)} (${style})` : JSON.stringify(run.text);
return li;
}));
status.textContent = `${bytes.length} bytes written, ${back.paragraphs} paragraph(s) and a table read back`;
saveButton.disabled = false;
});
saveButton.addEventListener('click', () => { if (bytes) DOWNLOAD.bytes(bytes, 'site-visit.docx', DOCX_TYPE); });index.html
<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ooxml · Write a .docx with the typed model, read it back</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
"@awacloud/ooxml": "/vendor/ooxml/main.js", "@awacloud/ooxml/": "/vendor/ooxml/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Write a .docx with the typed model, read it back</h1>
<p>
<button id="build" type="button">Build, write and read back</button>
<button id="download" type="button" disabled>Download site-visit.docx</button>
<span id="status" aria-live="polite"></span>
</p>
<h2>Text read back</h2>
<pre id="text"></pre>
<h2>Runs of the second paragraph</h2>
<ul id="runs"></ul>
</main>
<!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
<footer id="legal" aria-label="Legal notices">
<p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
<a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
<p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
<ul>
<li>@awacloud/fw · Apache-2.0</li>
<li>@awacloud/ooxml · AGPL-3.0-only</li>
</ul>
</footer>
<!-- aln:end -->
</body>
</html>