Open in a new tab

Build an .odt with a Title paragraph, typed runs (text, span, line break) and metadata (title, creator), download it, read it back and show toText, the runs and the metadata. The OpenDocument counterpart of ooxml/docx-write-read.

Uses @awacloud/odf (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.

When to use it

Producing an OpenDocument text file from application data in the browser — for LibreOffice users, public administrations and archives that require the ISO 26300 format — and checking what was written by reading it back with the same package.

Copy-paste steps

  1. npm install @awacloud/odf (it depends on @awacloud/fw).
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/odf/src/ at /vendor/odf/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy.
  4. Build your own body: odt.paragraph(text, { styleName }), typed run objects (text, span, line-break), odt.fromText(lines); pass { meta: { title, creator } } to write.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/odf's fw_require (XML and the zip closure) and modules arrays plus fw's download; rt.resolve('odt'). The @awacloud/odf/odt subpath is not served under /vendor/odf/, so a page takes odt from the root.
  • The model: { body: [...] } of paragraphs; a paragraph has runs — { type: 'text', value }, { type: 'span', value, bold: true } (the writer generates the text style; a styleName must name a style the document declares), { type: 'line-break' } — and an optional styleName (Title here).
  • Write: odt.write(doc, { meta }) returns the bytes of an ODF package: the mimetype entry first and stored, content.xml, meta.xml with dc:title, dc:creator and the package's meta:generator, styles.xml, the manifest. Two writes may differ in bytes (the zip writer stamps the time), so the test compares models and text.
  • Read: odt.read(bytes) returns { mimetype, body, meta, settings, styles, package, … } and refuses a package whose mimetype is not the text document type with a typed ParseError; odt.toText(result) joins paragraphs with newlines and turns a line break into a newline. The test checks the mimetype through the pkgPackage module as well, the text, the typed runs with their style name, the Title style and the metadata.
  • Not shown: lists, sections, tables (tableTable), images, named and automatic styles (styles, autoStyles), the odtLargeBundle / odtFullBundle coverage bundles and the opt-in extras.

Code

main.js

javascriptAGPL-3.0-only80 lines

// 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/odf';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules, download]);
const ODT = rt.resolve('odt');
const DOWNLOAD = rt.resolve('download');

/**
 * A typed document and its metadata: a `Title`-styled paragraph, a paragraph of
 * typed runs (`text`, a bold `span`, a `line-break`), and a
 * plain paragraph from `fromText`.
 * @param {{ title?: string, creator?: string }} [meta]
 */
export function buildDocument({ title = 'Site visit', creator = 'Example author' } = {}) {
    const body = [
        ODT.paragraph(title, { styleName: 'Title' }),
        // `bold: true` makes the writer generate the text style; a `styleName`
        // must name a style the document declares.
        { type: 'paragraph', runs: [
            { type: 'text', value: 'Measured on ' }, { type: 'span', value: 'site', bold: true },
            { type: 'line-break' }, { type: 'text', value: 'not assumed.' },
        ] },
        ...ODT.fromText(['Findings follow.']).body,
    ];
    return { doc: { body }, meta: { title, creator } };
}

/**
 * The `.odt` bytes: an ODF package (mimetype entry first, content.xml, meta.xml, …).
 * @param {ReturnType<typeof buildDocument>} built
 */
export const write = ({ doc, meta }) => ODT.write(doc, { meta });

/**
 * Read the bytes back: the package mimetype, the plain text (a line break
 * becomes a newline), the metadata and the typed runs of the second paragraph.
 * @param {Uint8Array} bytes
 */
export function readBack(bytes) {
    const result = ODT.read(bytes); // { mimetype, body, meta, settings, styles, package, … }
    const runs = result.body[1].runs.map((/** @type {any} */ run) => {
        if (run.type === 'line-break') return 'line-break';
        return `${run.type} ${JSON.stringify(run.value)}${run.bold ? ' (bold)' : ''}`;
    });
    return {
        mimetype: result.mimetype, text: ODT.toText(result), titleStyle: result.body[0].styleName ?? null, runs,
        meta: { title: result.meta?.title ?? null, creator: result.meta?.creator ?? null },
    };
}

const text = /** @type {HTMLElement} */ (document.getElementById('text'));
const runList = /** @type {HTMLElement} */ (document.getElementById('runs'));
const metaList = /** @type {HTMLElement} */ (document.getElementById('meta'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
const saveButton = /** @type {HTMLButtonElement} */ (document.getElementById('download'));
let bytes = /** @type {Uint8Array | null} */ (null);

/** @param {HTMLElement} list @param {string[]} items */
/** @param {HTMLElement} list @param {string[]} items */
const fill = (list, items) => list.replaceChildren(...items.map((item) => {
    const li = document.createElement('li');
    li.textContent = item;
    return li;
}));

document.getElementById('build')?.addEventListener('click', () => {
    bytes = write(buildDocument());
    const back = readBack(bytes);
    text.textContent = back.text;
    fill(runList, back.runs);
    fill(metaList, Object.entries(back.meta).map(([k, v]) => `${k}: ${v ?? '—'}`));
    status.textContent = `${bytes.length} bytes, ${back.mimetype}, title style ${back.titleStyle}`;
    saveButton.disabled = false;
});
saveButton.addEventListener('click', () => {
    if (bytes) DOWNLOAD.bytes(bytes, 'site-visit.odt', 'application/vnd.oasis.opendocument.text');
});

index.html

htmlAGPL-3.0-only44 lines

<!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>odf · Write an .odt with typed runs and metadata, 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/odf": "/vendor/odf/main.js", "@awacloud/odf/": "/vendor/odf/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Write an .odt with typed runs and metadata, 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.odt</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>
    <h2>Metadata</h2>
    <ul id="meta"></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/odf · AGPL-3.0-only</li>
    </ul>
  </footer>
  <!-- aln:end -->
</body>
</html>