Run it

Node Guide

The same Markdown to PDF twice: on a plain oconv runtime (Standard 14, the Cyrillic line is recorded as unencodable) and with registerDefaultFaces (Liberation embedded, no loss); ledgers and sizes compared. node kind.

Uses @awacloud/oconv-fonts (AGPL-3.0-only) with @awacloud/oconv (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only. The faces the package vendors are Liberation 2.1.5 under the SIL Open Font License 1.1 (Reserved Font Names Liberation, Arimo, Tinos, Cousine), as its README and vendor/OFL.txt state.

When to use it

Generating PDFs from Markdown for readers whose text goes beyond the Western European range a viewer's built-in fonts can show — Cyrillic, most of Greek, extended Latin — without supplying your own font files: one registration call switches every style class to an embedded Liberation face and the loss ledger stops reporting unencodable text.

Copy-paste steps

  1. npm install @awacloud/oconv @awacloud/oconv-fonts (they depend on @awacloud/fw and the office packages).
  2. Copy main.js and run bun main.js out/ (or node main.js out/): it writes standard14.pdf and liberation.pdf and prints one line per route with the size, whether a font program is embedded, and the ledger.
  3. In your own code, build the runtime in this order: registerAll(fw_require), await registerDefaultFaces(runtime), registerAll(modules), then resolve('oconv'). Registering the pack after the first resolve needs runtime.invalidate('oconvDefaultFaces', { cascade: true }).

What it shows

  • Two runtimes, one source: compare(markdown) builds a plain oconv runtime and a second one with the face pack registered, and runs fromMd({ markdown, target: 'pdf' }) on both. Each example here uses its own ModuleRuntime; the pack is resolved by name (oconvDefaultFaces), never imported by @awacloud/oconv.
  • Standard 14: the viewer's resident fonts (/BaseFont /Helvetica), WinAnsi text only. Accented Latin (café, Ærø) is representable; the Cyrillic line is drawn as ? and recorded once as text/unencodable with { count, sample } — nothing is silently dropped. Pure Standard 14 is a route, not a fallback: no layout/font-fallback is recorded.
  • Liberation: registerDefaultFaces(runtime) fetches the five faces relative to the package's module URL (file: under Bun and Node) and the writer embeds a subset (/FontFile2, /BaseFont /XXXXXX+LiberationSans); the ledger is empty and the file is larger by the embedded programs. The coverage is a cmap fact the package measures (Latin, Cyrillic 100 %, Greek 88 %); scripts outside it still record text/unencodable.
  • In a page: there is no /vendor row for oconv-fonts, so this example is a script. A page would serve the package's src/ and vendor/liberation/ directories and call registerDefaultFaces(runtime, { baseUrl }) with the directory that serves the five .ttf files; the package fetches them relative to its own module URL by default.
  • Not shown: loadDefaultFaces() for passing the bytes as opts.pdf.fonts, mixing explicit faces with the pack (layout/font-fallback on the classes left out), the other fromMd targets.

Code

main.js

javascriptAGPL-3.0-only80 lines

// SPDX-License-Identifier: AGPL-3.0-only
// Run: bun main.js <out-dir>   (or node main.js <out-dir>)
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';
import { registerDefaultFaces } from '@awacloud/oconv-fonts';

/** English, accented Latin (WinAnsi can hold it) and a Cyrillic line (it cannot). */
export const SAMPLE = '# Field notes\n\nPlain English first, then accented Latin: café, déjà vu, Ærø.\n\n'
    + 'А теперь строка по-русски: привет, мир.\n';

/** The default route: oconv alone, every style class on a PDF Standard 14 face. */
function standard14() {
    const rt = new ModuleRuntime();
    rt.registerAll([...fw_require, ...modules]);
    return rt.resolve('oconv');
}

/**
 * The face-pack route: `registerDefaultFaces` fetches the five Liberation
 * faces relative to the package's own module URL and registers the
 * `oconvDefaultFaces` descriptor. Register it BEFORE the first `resolve('oconv')`
 * on that runtime (the package's README order), or invalidate afterwards.
 */
async function liberation() {
    const rt = new ModuleRuntime();
    rt.registerAll(fw_require);
    await registerDefaultFaces(rt);
    rt.registerAll(modules);
    return rt.resolve('oconv');
}

/**
 * The same Markdown to PDF twice. Each result carries the bytes and the loss
 * ledger: on the Standard 14 route non-WinAnsi text is drawn as `?` and
 * recorded once as `text/unencodable`; with the Liberation faces registered
 * the covered scripts (Latin, Cyrillic, most of Greek) draw with no loss.
 * @param {string} [markdown]
 * @returns {Promise<{ standard14: { bytes: Uint8Array, losses: { code: string, detail: unknown }[] },
 *   liberation: { bytes: Uint8Array, losses: { code: string, detail: unknown }[] } }>}
 */
export async function compare(markdown = SAMPLE) {
    const [s14, lib] = await Promise.all([
        standard14().fromMd({ markdown, target: 'pdf' }),
        (await liberation()).fromMd({ markdown, target: 'pdf' }),
    ]);
    return {
        standard14: { bytes: s14.bytes, losses: s14.losses }, liberation: { bytes: lib.bytes, losses: lib.losses },
    };
}

/** `true` when the PDF carries an embedded TrueType program. @param {Uint8Array} bytes */
export const embedsFontProgram = (bytes) => new TextDecoder('latin1').decode(bytes).includes('/FontFile2');

/** Stable report lines: sizes, embedding, ledgers. @param {Awaited<ReturnType<typeof compare>>} result */
export function report({ standard14: s14, liberation: lib }) {
    const ledger = (/** @type {{ code: string, detail: unknown }[]} */ losses) => (losses.length
        ? losses.map((l) => `${l.code} ${JSON.stringify(l.detail)}`).join('; ')
        : 'no loss');
    const line = (/** @type {string} */ label, /** @type {typeof s14} */ r) => `${label}: ${r.bytes.length} bytes, `
        + `embedded font program: ${embedsFontProgram(r.bytes) ? 'yes' : 'no'}, ledger: ${ledger(r.losses)}`;
    return [line('Standard 14', s14), line('Liberation', lib)];
}

/** @param {string[]} [argv] */
export async function main(argv = process.argv.slice(2)) {
    const [outDir] = argv;
    if (!outDir) return ['usage: bun main.js <out-dir>'];
    const result = await compare();
    mkdirSync(outDir, { recursive: true });
    writeFileSync(join(outDir, 'standard14.pdf'), result.standard14.bytes);
    writeFileSync(join(outDir, 'liberation.pdf'), result.liberation.bytes);
    return [...report(result), `written to ${outDir}: standard14.pdf, liberation.pdf`];
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    for (const line of await main()) console.log(line);
}