oconv-ir/v2 → .pdf bytes — the bounded typesetter's writer facade.

Module oconvIrToPdf | Source packages/front/office/oconv/src/write/ir-to-pdf.js | Deps oconvIr, oconvPdfMetrics, oconvPdfBox, oconvPdfLinebreak, oconvPdfStack, oconvPdfRenderText, oconvPdfRenderList, oconvPdfRenderCode, oconvPdfRenderTable, oconvPdfRenderImage, pdfBuilder, pdfFontEmbed, fonts, oconvDefaultFaces, zlib (optional), standard14Lookup (optional, last) | Worker-safe yes

This is the only module in the family that talks to @awacloud/pdf. It owns the whole md → pdf write pipeline: option validation (oconvPdfBox.resolveLayout), font-route resolution (oconvPdfMetrics.createMeasurer), flow + page stacking (oconvPdfStack.layoutDocument), the renderer dispatch for list/codeBlock/table/image, content-stream emission (oconvPdfRenderText.pageContent) and final assembly through pdfBuilder.

Resolve

import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';

const runtime = new ModuleRuntime();
runtime.registerAll(fw_require);
runtime.registerAll(modules);
const oconvIrToPdf = runtime.resolve('oconvIrToPdf');

Reached in practice through oconv.fromMd({ markdown, target: 'pdf' }) or oconv.convert({ ..., target: 'pdf' }) (../oconv.md) — see pdf-writer.md for the full options/route/loss-code reference from that public entry point.

API

Member Signature Returns Throws
RESOURCE_NAMES {regular: 'FR', bold: 'FB', italic: 'FI', boldItalic: 'FZ', code: 'FM'} style class → PDF resource name —
irToPdf `(ir: object, pdfOpts?: object, writeOpts?: {assets?: Object<string, Uint8Array>, defaultFaces?: Object<string, Uint8Array> null}) => IrToPdfResult` {bytes: Uint8Array, losses: IrToPdfLoss[], pages: number}

Throws: oconv: bad pdf option <key> (an unrecognised pdfOpts key, via oconvPdfBox.resolveLayout); oconv: bad pdf font <style> / oconv: bad default font <style> (unreadable font bytes or an unknown pdfOpts.fonts/writeOpts.defaultFaces key, via oconvPdfMetrics.createMeasurer); oconv: invalid ir (<code> at <path>) when ir fails oconvIr.validate.

pages is the number of pages the document actually laid out onto — the caller-facing return that lets an integrator know the page count without re-parsing the produced bytes.

pdfOpts (the opts.pdf block)

Validated in exactly ONE place, oconvPdfBox.resolveLayout:

Key Type Default Validation error
pageSize 'A4' | 'Letter' | [width, height] (pt, both > 0) 'A4' (595.276 × 841.89 pt) oconv: bad pdf option pageSize
margin number ≥ 0, 2·margin < the smaller page dimension 56.693 pt (20 mm) oconv: bad pdf option margin
baseSize number > 0 11 pt oconv: bad pdf option baseSize
leadingRatio number > 0 1.32 oconv: bad pdf option leadingRatio
headingScale number[6], all > 0 (levels 1-6, absolute pt) [22, 18, 15, 13, 12, 11] oconv: bad pdf option headingScale
codeSize number > 0 9.5 pt oconv: bad pdf option codeSize
pageNumbers boolean true oconv: bad pdf option pageNumbers
fonts {regular?, bold?, italic?, boldItalic?, mono?: Uint8Array} {} (pure Standard 14) accepted-and-forwarded here; failures surface from oconvPdfMetrics
pdfA '4' | '2b' absent (no claim) oconv: bad pdf option pdfA; forwarded to pdfBuilder's builder({ pdfA }) (XMP, sRGB output intent, the profile's version); every drawn style class needs an embedded face, else oconv: pdf/A needs embedded faces (<classes>) before writing
pdfUA 1 | 2 absent (no claim) oconv: bad pdf option pdfUA (also with pdfA); forwarded to pdfBuilder's builder({ pdfUA, lang }): the document is tagged (see Tagged output); every drawn style class needs an embedded face, else oconv: pdf/UA needs embedded faces (<classes>) before writing
lang non-empty string (a BCP 47 tag) absent oconv: bad pdf option lang — required with pdfUA, refused without it

Any other key throws oconv: bad pdf option <key>; a non-object, non-undefined, non-null pdfOpts throws oconv: bad pdf option pdf.

The font routes, resolved per style class

explicit pdfOpts.fonts[class] > registered/posted oconvDefaultFaces[class] > Standard 14
  • Standard 14 (default) — one addFont({ name, baseFont, subtype: 'Type1', encoding: 'WinAnsiEncoding' }) per style class the document uses (Helvetica/Helvetica-Bold/ Helvetica-Oblique/Helvetica-BoldOblique/Courier); no font program is embedded, vendored or downloaded. WinAnsi (CP1252) literal-string encoding, declared on every font dict as /Encoding /WinAnsiEncoding.
  • Embedded (explicit pdfOpts.fonts or a default face) — the resolved face is parsed by @awacloud/fonts, subset to the exact code points the laid-out document uses, and embedded via pdfFontEmbed.embedSimple (every code point WinAnsi-representable) or embedCid otherwise (Identity-H hex strings). pdfBuilder caches an embed result by identity so N pages sharing a style share ONE font object.
  • The default-face tier is reached ONLY by the module NAME oconvDefaultFaces — this facade never imports a face pack. main.js registers a stand-in at version 0.0.0 whose defaultFaces() returns null; a real pack (e.g. @awacloud/oconv-fonts, version 1.1.0) displaces it in either registration order. See pdf/default-faces for the full stand-in contract and pdf-writer.md for the host registration recipe.

A style class resolved from Standard 14 while at least one other class is embedded (explicit or default) records layout/font-fallback; on the pure Standard 14 route (no pdfOpts.fonts, no registered/posted default map at all) nothing is recorded — it is the chosen route, not a fallback. A caller face (explicit or default) that @awacloud/fonts reads but that has no TrueType outlines — a CFF / CFF2 OpenType face, which subsetForPdf cannot subset — is not embedded: its class falls back to Standard 14 and records layout/font-fallback with reason: 'no TrueType outlines' in its detail, on every route (the face was asked for).

Images

writeOpts.assets carries { '<markdown image destination>': Uint8Array } down to oconvPdfRenderImage. Placed, drawn q w 0 0 h x y cm /Im<n> Do Q, no loss: a JPEG (baseline/extended/progressive, 1 or 3 components) with /DCTDecode, and a PNG — a non-interlaced PNG of colour type 0 or 2 without tRNS embeds its IDAT zlib stream verbatim as /FlateDecode behind a PNG /Predictor 15; a palette, alpha or colour-key PNG is inflated (bounded by its IHDR size), unfiltered and split into its colour samples (a palette expanded to 8-bit RGB) and a DeviceGray /SMask, both re-deflated. The decoding uses fw zlib, an optional dependency of this facade (ctx.zlib for the renderer): a hand-wired factory call without it refuses those PNGs. The LAST dependency, standard14Lookup (optional too), reaches every Standard 14 registration as pdfBuilder.addFont's standard14 option, so the font dictionaries carry the FirstChar, LastChar, Widths and FontDescriptor PDF 2.0 requires; a hand-wired call without it writes the bare dictionaries. Every other case is refused with the italic [image: <alt>] placeholder still drawn and one layout/image-dropped loss, reason: 'unsupported-encoding': an interlaced or malformed PNG, or one above 64 MiB of filtered data (format: 'png'), a CMYK JPEG (format: 'jpeg'), a GIF, WebP, BMP or TIFF (named from its signature), anything else (named from the content type a reader carried, else no format); nothing resolved at all → reason: 'no-bytes', bytes: 0. See pdf-writer.md for the full placement geometry and format boundary.

Tagged output (PDF/UA)

Under pdfUA the typesetter marks every drawn item with its structure element (pdfBuilder's openElement / markContent / closeElement), one Document holding:

IR Structure
heading H1–H6
paragraph P
blockquote BlockQuote holding its blocks (PDF/UA-2: Div)
list / listItem L (ListNumbering as drawn: Disc, or Decimal / LowerAlpha / LowerRoman by depth), LI, Lbl (the marker), LBody (the item's blocks)
table / row / cell Table, TR, TH (a header row's, Scope Column) or TD, holding the cell's blocks
codeBlock Code in a P (PDF/UA-2: the P)
image Figure with its alt text; the placeholder text of a refused image a P

Rules (the thematic break, quote bars, table rules) are artifacts, page numbers /Pagination artifacts. A picture without alt text is decorative: an artifact, recorded image/decorative ({ index, name }). PDF/UA-2 writes the PDF 2.0 standard types: it has no BlockQuote or Code, which veraPDF refuses there (rule 8.2.4). The title, required: writeOpts.title (fromMd's front matter title, convert's source title), else the first heading's text; neither is oconv: pdf/UA needs a title (front matter or a heading). With the default faces, veraPDF 1.30.3 judges the documents conforming to the part claimed (verapdf-pdfua).

Examples

Standard 14 (default) — no options

// Build the IR with the oconvIr helpers: `irToPdf` validates its input, and
// a bare `{ kind: 'run', text }` literal fails with `bad-prop`.
const { node, doc } = runtime.resolve('oconvIr');
const ir = doc([
    node('heading', { level: 1 }, [node('run', { text: 'Title' })]),
    node('paragraph', {}, [node('run', { text: 'Hello world' })])
]);
const { bytes, losses, pages } = oconvIrToPdf.irToPdf(ir, { pageNumbers: false });
// bytes — a non-empty .pdf Uint8Array; losses deep-equals []; pages === 1

Executed against the live package (2026-10-03): bytes instanceof Uint8Array, pages === 1, losses is [].

Notes

  • Determinism: irToPdf injects NO date and sets no document /ID — only addMetadata({Producer, Creator}), never setId; @awacloud/pdf's writer derives the trailer /ID PDF 2.0 requires from the bytes it wrote (a SHA-256), so the output stays reproducible. @awacloud/pdf's plain write path reads no clock and no randomness; this holds only on that path — document/encryptedWriter.js uses Math.random() for its file key, and md → pdf never enters it.
  • Every drawn segment has a font entry — collectCodePoints keys any style outside oconvPdfMetrics.STYLE_CLASSES as regular, so fonts[style] || fonts.regular is always defined for every segment a renderer actually draws; oconv: pdf font missing <style> is a violated-invariant guard, unreachable through the shipped renderers and valid IR.
  • text/unencodable is route-conditional but always ONE record per document: on the Standard 14/WinAnsi route it counts code points outside WinAnsi (drawn as ?); on an embedded/default-face route it counts code points with no glyph in the resolved face's own cmap (hasGlyph, drawn as .notdef) — previously silent on that route, now always recorded.
  • CP1252 text decodes through the declared encoding: on the Standard 14 route the text bytes are CP1252 and each font dict names /Encoding /WinAnsiEncoding, so bytes 0x80–0xFF read back as the characters drawn (Café, déjà, the em dash, the •/– list markers) rather than as the font's built-in StandardEncoding glyphs.
  • Two inline styles are recorded, not drawn: a struck run (inline/strike-dropped) and a monospace run that is also bold or italic (inline/code-emphasis-dropped) — one record per text block, from pdf/linebreak, carrying the block's {index, kind}. The drawn bytes are those of the unflagged run.
  • Full loss-code table, error catalogue, worker-boundary behaviour (opts.pdf crosses, the oconvDefaultFaces descriptor never does) and the keepTogether design note are on pdf-writer.md — not restated here to avoid two copies drifting apart.
  • See the loss matrix for the published Preserved/Degraded/Dropped classification.

See also