Skip to main content

Chapter 3.16 · Part II · The craft

Configuration: fonts, colours and output

Units, colours and the palette, custom fonts, the HTML viewer, PDF and print production, the Folio viewer and the debug overlays

Updated 2026-11-1037 minIn chapter 3 Configurationenescadefritptzhjaar

In short

This page covers the settings shared by the whole book and the settings for each kind of output. It explains how to write a measure and a colour, and how to name the colours of a palette. It shows how to add your own fonts. Then it covers the web view, the PDF file, the files a printing company asks for and the 3D book. The last section turns on the guides and warnings that help while you work.

#Units and colors

#Dimensions

All physical measurements in Postext use the Dimension type — a value paired with a unit:

interface Dimension {
  value: number;
  unit: DimensionUnit; // 'cm' | 'mm' | 'in' | 'pt' | 'px' | 'em' | 'rem'
}

Absolute units — cm, mm, in, pt, px — are converted to pixels using the configured DPI. At 300 DPI, 1 cm equals approximately 118 px.

Relative units — em, rem — scale with the current font size. An em is relative to the element's own font size; rem is relative to the body text font size.

#Colors

Colors are stored with both a hex representation and a target color model:

interface ColorValue {
  hex: string;         // '#ff0000', 'transparent', etc.
  model: ColorModel;   // 'hex' | 'rgb' | 'cmyk' | 'hsl' | 'spot'
  cmyk?: CmykPercent;  // The exact process values of a colour authored in CMYK.
  spot?: SpotColor;    // The ink of a spot colour (see Spot colours).
  overprint?: boolean; // Overprints in a print render (see Colours that overprint).
  paletteId?: string;  // The colorPalette entry it follows (see Color Palette).
  tint?: number;       // The strength of the entry over the page colour, percent (with paletteId).
}

The model field indicates the intended color space. For web rendering, 'hex' or 'rgb' are typical. For print workflows, 'cmyk' says the colour was specified in CMYK, and cmyk keeps its values: a CMYK print render sets them as they are, with hex as their screen rendering (see Colours authored in CMYK). 'spot' is a spot colour, with its ink in spot (see Spot colours).

Because Postext targets publication-grade output, the default body text color ships with model: 'cmyk' (#000000). Heading, bold, italic, and list colors default to the palette-linked Main Color (#295AA3, model: 'hex'). Page background and UI overlays (baseline grid, cut marks, debug indicators) default to model: 'hex'. Override color.model on any field if you need different export semantics.

#Transparency

A colour can be translucent. hex accepts an alpha channel, as #rgba or #rrggbbaa. It also accepts an rgb() / rgba() colour, in the comma or the space syntax, with the alpha as a number or a percentage. transparent is fully clear:

const config: PostextConfig = {
  header: {
    elements: [{
      kind: 'box',
      id: 'veil',
      placement: {
        anchor: { to: 'bleed', edge: 'top-left' },
        size: { width: 'fill', height: { value: 40, unit: 'mm' } },
      },
      style: { backgroundColor: { hex: '#ffffffb3', model: 'hex' } }, // white at 70 %
    }],
  },
  bodyText: { color: { hex: 'rgba(0, 0, 0, 0.85)', model: 'rgb' } },
};

The three backends paint it the same way. The canvas and the HTML viewer take the value as a CSS colour. The PDF backend sets the colour's opacity as a constant alpha, an ExtGState with ca for fills and CA for strokes. This covers text, rules, boxes, table fills and borders, chips, swatches and formulas. A translucent colour composes over whatever was painted before it. A box in the header or footer is painted last, so it veils the text under it; a box in an opener band is painted first, so it tints the page under the text. When the PDF is forced into another colour space (pdfGeneration.forceColorSpace with colorSpace: 'cmyk' or 'grayscale'), the colour is converted and its alpha kept. In the Sandbox, the opacity slider of the colour picker writes these values as #rrggbbaa, and the picker reads the other forms too.

#Custom fonts

Postext resolves every fontFamily string against both the Google Fonts catalogue and the document's customFonts list. Custom fonts take precedence on name collision — if you declare customFonts: [{ name: 'Roboto', … }], Postext uses your uploaded file instead of the Google Fonts "Roboto". The Sandbox takes a family Google Fonts does not have from Fontsource. It never asks Fontsource for a generic name (serif, system-ui) or a face an operating system ships (Arial, Segoe UI, PingFang SC…): such a family is set in whatever the reader's machine has, the Fonts panel shows it as Not found, and the PDF and the SVG pictures have no file of it to embed. Upload the face as a custom font when the book is set in it.

Use custom fonts when:

  • The document needs a brand or licensed typeface that is not on Google Fonts.
  • The environment can't reach the font CDNs, jsDelivr (where the Sandbox takes Fontsource's files from) or Google Fonts (offline, intranet, privacy-sensitive).
  • You must keep the font binary private and not upload it to a third party.

#Configuration schema

type CustomFontFormat = 'woff2' | 'woff' | 'ttf' | 'otf';
type CustomFontStyle = 'normal' | 'italic';
 
interface CustomFontVariant {
  weight: number;           // CSS font-weight, 100..900
  style: CustomFontStyle;
  fileId: string;           // opaque id of the binary in out-of-band storage
  format: CustomFontFormat;
  fileName?: string;        // original upload filename (optional, shown in UI)
}
 
interface CustomFontFamily {
  name: string;             // used anywhere a Google Font family name fits
  variants: CustomFontVariant[];
  redistributable?: boolean; // false: used here, never copied out of the book
  fallback?: string;        // an open family of similar width for the faces it has no file of (since postext 1.42)
}
 
interface PostextConfig {
  // ...
  customFonts?: CustomFontFamily[];
}

Each variant's binary is not embedded in the config itself. The config only holds fileId pointers; the bytes live out-of-band. In the sandbox, that means IndexedDB (a key-value store in the browser, private to the document). An integrator embedding Postext in another host is free to resolve fileId however they like — a server endpoint, a service worker cache, anything — as long as the bytes reach the main thread before buildDocument runs.

#Managing custom fonts in the sandbox

Open the Fonts panel from the left activity bar (between Resources and Design). Its Typefaces in this book list shows every family the design uses, with its role and where it comes from: Google Fonts, Fontsource (for a family Google Fonts does not have), your file, or nowhere (Not found). Under Your font files, for each family:

  1. Add font family — creates an empty family; rename it inline.
  2. Upload file — pick a weight (100–900) and style (normal / italic), then choose one or many .woff2, .woff, .ttf, or .otf files. Each file becomes its own variant bound to the currently-selected (weight, style); the uploaded filename is remembered and shown in the row so you can tell variants apart. Re-tune a variant's weight or style from its dropdowns at any time.
  3. Duplicate variants are allowed. If two files land on the same (weight, style) slot, both are kept and a Duplicate font variant warning appears so you know to disambiguate the settings of the extras.
  4. Delete variant or Delete family — removes the entry from the config and the stored bytes from IndexedDB.

Once a family is declared, every font picker groups it under Custom, above the Google Fonts list. Selecting it wires the family into every font-family field you apply it to.

#A stand-in for a licensed family

A book can be set in a face its owner may not hand on. Mark the family redistributable: false and a .postext file leaves its files out. Name an open family of about the same width in fallback, and a file opened without those files still breaks its lines close to where the real face does, instead of overflowing its frames in a wider fallback font. Faces the family has no file for are set in the fallback's cuts of the same weight and slant, under the licensed name, in the previews, the layout worker, the PDF and the command line. A family with files keeps them; it takes from the fallback only a slant it has no file for, an italic for example, and the weights between its own files are chosen as for any family. In the Fonts panel, Stand-in family (inside the family, above its files) takes the name, and an empty field leaves the family as it was. The PDF of a book set this way embeds the open face, so the final PDF is made with the licensed files. Since postext 1.42. Since postext 1.43 the open face also goes where the licensed one may not: an EPUB or an HTML export, from the Sandbox or from postext, carries the fallback's faces under the licensed name, and so do the SVG pictures whose text is set in that family, so a reading system sets the book in a face of the width its lines were broken for. The family's own files never leave the book. A family without a fallback, or one whose fallback has no file, is named without files as before; the Sandbox's EPUB tab lists the families set in a stand-in.

#Rendering behaviour

Under the hood:

  • When customFonts changes, every declared family is automatically registered as FontFace entries on document.fonts — so the HTML viewer, the Canvas viewport (which measures through document.fonts), and any direct CSS reference all pick up the custom face without requiring the user to first open the Font Picker.
  • The layout worker receives the same ArrayBuffers through the existing font payload transfer path, so measurement (buildFontString, pretext) works as it does for a family of the catalogue.
  • Changing or removing a variant drops the worker's cached face for that family and re-registers on the next build, so previews stay in sync with the current variant set.
  • PDF export: uploaded binaries flow through the same PdfFontProvider pipeline. .woff2 files are decompressed; .ttf and .otf are passed through directly. .woff is rejected with a clear error (pdf-lib can't embed raw WOFF — re-upload as .woff2/.ttf/.otf). CFF-flavored OpenType (.otf with OTTO magic) is embedded without subsetting, because pdf-lib's CFF subsetter walks every glyph at save() time and can hang for minutes on real fonts; skipping the subset trades a somewhat larger PDF for consistent render times. The face is declared as CFF (CIDFontType0, FontFile3 / CIDFontType0C), so a print preflight sees what it is; a CID-keyed CFF face (Source Han, Noto CJK .otf) keeps the TrueType declaration.

#Missing-font warnings

The Sandbox's Checks panel lists three failure modes specific to custom fonts under its Fonts group (all enabled by the same debug.warnings.missingFont toggle that already guards the generic "not loaded" warning):

  • Unknown font family — a fontFamily references a name that neither Google Fonts nor Fontsource has and that is not a currently-declared custom family. This also fires immediately when you delete a custom family that some fontFamily field still references, instead of waiting for the DOM to notice.
  • Missing font variant — the family exists, but the book asks it for a weight and style that has no uploaded file: bold headings, say, in a family with only a regular face. The warning lists the combinations that are missing. A slant the family's fallback sets is not missing.
  • Duplicate font variant — two or more uploaded files share the same (weight, style) slot within one family. Only one file is actually used at render time; the warning nudges you to retune the remaining entries.

Clicking any of these warnings opens the Fonts panel so you can upload the missing variant, re-add the family, or disambiguate the duplicates.

Once a layout exists, the panel also lists the engine's Font fallback in the layout (fontFallback): a face the pages were measured without, either missing or drawn by the browser from another weight or slant. A family already named as unknown or short of a variant is not listed twice. Before the first layout, a check against document.fonts stands in for it.

The panel also lists Characters drawn from another face (glyphFallback): characters the text sets in a face that has no glyph for them, once per face, with the generic family that drew them (serif, sans-serif, monospace) when the check can tell.

#Symbol font

A text font rarely has the mathematical letters and operators (∪, ℵ, ∀), the Greek or the arrows an author types in a paragraph. symbolFont names a family that sets them: every font of the document lists it after its own, so the canvas, the PDF, the HTML and the EPUB draw those characters in it instead of an empty box. 'Noto Sans Math' covers most mathematics. In the Sandbox it is Body text → Symbol font. The formatted Word file sets those characters in runs of it too. Its regular face draws for every weight and slant of the text.

The layout reports each paragraph that sets such characters as glyphFallbackAt, with the family that draws them, or none: the PDF then prints them as empty boxes. The Sandbox marks those characters on the page, violet where the symbol font draws them and red where nothing does.

#Figure styles

figureStyle asks a text style's font for one kind of figures, through the font's OpenType features: old-style figures in the running text, lining tabular figures in the tables. The field is on bodyText, paragraphStyles[], headings and headings.levels[], headingStyles[], tableStyle and tableStyles[] (header and body cells alike), captionStyle (label and description, and the captionStyle of a resource type) and the text elements of a design (running heads, folios, the texts of an opener or a part page). In the Sandbox it is the Figures field of the Design panel, next to the typeface of each of those styles (Body text → Typeface for the body).

ValueOpenType featuresFigures
'default'noneThe font's own. Takes off the figures a style inherits.
'oldstyle'onumOld-style figures, with ascenders and descenders like lower-case letters: running text.
'lining'lnumLining figures, at cap height: headings, text in capitals.
'tabular'tnumEvery figure on the same width, so the digits of a column line up. The form stays the font's.
'proportional'pnumEach figure on its own width. The form stays the font's.
'oldstyle-tabular'onum + tnumOld-style figures on one width.
'oldstyle-proportional'onum + pnumOld-style figures on their own widths.
'lining-tabular'lnum + tnumLining figures on one width: tables, timetables, price lists.
'lining-proportional'lnum + pnumLining figures on their own widths.

A pair sets a form and a width. A font without the feature keeps its own figures, so check that the face has onum or lnum before relying on it. A family the host has no file of, such as a face only installed on the reader's system (the Sandbox does not fetch those), takes no figure style: its text keeps that font's own figures, in the font itself. A book that uploads files under that name gets the figures. The cuts Google Fonts and Fontsource serve often leave onum and lnum out (the latin file of Source Serif 4 keeps only pnum and tnum); with such a file, a style that asks for them keeps the font's own figures. The foundry's full files have them: upload those to get old-style or lining figures. A generic family (serif, sans-serif) takes no features. A value outside the list is reported as an unknown setting value (unknownConfigValue, see Configuration warnings) and read as unset.

const config: PostextConfig = {
  bodyText: { fontFamily: 'EB Garamond', figureStyle: 'oldstyle' },
  tableStyle: { figureStyle: 'lining-tabular' },
  paragraphStyles: [{ id: 'timetable', figureStyle: 'lining-tabular' }],
  headings: { figureStyle: 'lining' },
};

The prose sets its years and page numbers in old-style figures, and so do the captions and the lists, which take the body's family. The cells of every table and the paragraphs of the timetable style line their digits up in lining tabular figures. Every heading level sets lining figures in the headings' family.

#Which figures a style takes

  • A style that takes its family from another takes its figures too. Paragraph styles, tables, captions, lists and the bodies of boxes take the body's family when they name none, so bodyText.figureStyle reaches all of them.
  • A style that names its own fontFamily sets that font's default figures, unless it also sets figureStyle.
  • A heading level without a figureStyle of its own takes headings.figureStyle, in its own fontFamily too when it names one. A heading style's figureStyle applies to the family of the level the style is set on.
  • A design text element names its own family ('EB Garamond' by default), so the body's figures do not reach a folio: set figureStyle: 'oldstyle' on it to match old-style text.
  • 'default' sets the font's own figures and undoes inherited ones: paragraphStyles: [{ id: 'plain', figureStyle: 'default' }] drops the body's old-style figures in that style.

#Figures in each output

The text is measured with the features, so its lines break on the same widths in the canvas preview, the HTML, the PDF and both EPUB layouts.

  • Canvas preview and layout worker: the browser declares the base family's files a second time, under a feature family name, with the featureSettings descriptor of FontFace. The name is the family and its features after @ (EB Garamond@onum, EB Garamond@lnum+tnum), and it shows in font strings and in some warnings.
  • HTML and EPUB (fixed and reflowable): the base family, with font-variant-numeric (oldstyle-nums, lining-nums tabular-nums).
  • PDF: the base family's files are embedded and the text is laid out with the features.
  • Command line: Skia, the canvas postext draws with, sets no features. The command line registers a copy of the font whose cmap maps each character the features substitute, the digits, to the glyph they choose. Only single substitutions are taken; a font that reaches its figures through contextual lookups keeps its own figures there.

#Color Palette

The colorPalette property on PostextConfig lets you define a reusable set of named colors and reference them from any ColorValue in the configuration. It is the Postext equivalent of CSS custom properties or an InDesign swatches panel: change the palette entry once, and every color that points to it updates across the document.

interface ColorPaletteEntry {
  id: string;       // stable identifier — referenced by ColorValue.paletteId
  name: string;     // human label shown in sandbox UIs
  value: ColorValue;
}

#The default palette

Postext ships with a single-entry default palette called Main Color (id: 'main-color', hex #295AA3). Several defaults — heading color, bold/italic body color, :ref color, bullet and number-marker colors — reference this entry via paletteId: 'main-color', so changing that one swatch retints every part of the document that uses it.

You can inspect, clone, or compare against the default palette via three exports:

import {
  DEFAULT_COLOR_PALETTE,
  cloneDefaultColorPalette,
  isDefaultColorPalette,
} from 'postext';
 
// Read-only snapshot of the shipped palette.
DEFAULT_COLOR_PALETTE;
// => [{ id: 'main-color', name: 'Main Color', value: { hex: '#295AA3', model: 'hex' } }]
 
// Independent copy — mutate this, not DEFAULT_COLOR_PALETTE.
const palette = cloneDefaultColorPalette();
 
// Detect whether a user has customised the palette at all.
isDefaultColorPalette(palette); // true

A palette lives at the top level of the config:

const config: PostextConfig = {
  colorPalette: [
    { id: 'ink',    name: 'Ink',    value: { hex: '#0a0a0a', model: 'cmyk' } },
    { id: 'accent', name: 'Accent', value: { hex: '#b8860b', model: 'hex' } },
  ],
  bodyText: { color: { hex: '#000000', model: 'cmyk', paletteId: 'ink' } },
  headings: { color: { hex: '#000000', model: 'hex', paletteId: 'accent' } },
};

#Referencing a palette entry

Any ColorValue in the configuration can carry an optional paletteId field pointing at an entry in colorPalette: page background, body text colors (the :ref colour included), heading colors, column rules, list colors, table, caption, chip and callout colors (box, stripe, icon, marker, label, title, body), cut-mark and baseline-grid colors, debug indicators, and every colour of a design — the running heads, the heading openers and in-column designs, the heading styles' designs and running heads, the part pages and the contents' part rows (text, rule, box fill and border, outline, drop cap). When present, the palette entry's hex / model win over the fallback hex / model stored alongside. The inline fallback is only used if the palette is missing, empty, or doesn't contain that id — useful when shipping a config that will be read by a tool that doesn't understand palettes.

Changed in postext 1.5. Up to postext 1.4 the palette reached only a fixed list of settings. The others — the colours of the designs (running heads, openers, heading styles, parts, contents rows), bodyText.referenceColor, the callout label colours and the bold / italic colours of callout bodies — kept the hex stored beside their paletteId. A document whose stored value differs from the palette entry — every one edited in the Sandbox after the entry changed, and every :ref when the Main Color is not #295AA3 — now prints the palette colour, as the link says. To keep a colour as it was, remove its paletteId.

A tint of a palette entry. With paletteId, tint (0–100) paints the entry at that strength: { hex: '#eef2f8', model: 'hex', paletteId: 'main-color', tint: 8 } is the main colour at 8 %, a callout ground that follows the main colour when the palette changes. A part's or a section's palette keeps the strength everywhere it recolours: the flow, the page colour, the line numbers, table cells, the design slots and the Word export. The tint keeps the entry's model: a CMYK entry gives its inks scaled (10 % of 100 60 0 10 prints 10 6 0 1), a spot entry gives a tint of the same ink on its own plate, and a screen colour mixes with the page colour (page.backgroundColor, white when unset; under a CMYK tint, a page colour authored in CMYK adds its own inks). hex keeps the tinted value, the fallback without the entry. A spot tint carries one ink only: over a coloured page it knocks the page colour out unless it overprints. In the Sandbox, a linked colour's picker has a Tint field.

#How palettes are applied

buildDocument runs the palette in two places so referenced colors work both for overrides you spelled out and for defaults that are filled in later:

  1. applyPaletteToConfig(config) — resolves every ColorValue in the raw user config that carries a paletteId. Useful when you want to inspect what the engine will actually see.
  2. applyPaletteToResolvedConfig(resolved, palette) — runs after defaults are resolved and rewrites the palette-linked defaults (heading color, bold/italic body color, :ref color, list colors, the colours of the default designs) to match the active palette.

Both walk the whole configuration, so no palette-linked colour is left behind. Most colours of the text flow (body text, headings, lists, tables, captions, chips, the callout box, title and body) come out as plain values. Every other one — the colours of the designs, the :ref colour, the callout labels — takes the palette's hex / model and keeps its paletteId. That link is what a part's palette attribute and a heading style's palette override on their pages (see Parts), so it has to survive. htmlViewer.overrides is left as written: the HTML viewer merges it first, and a palette it carries then applies to everything, the designs included.

You rarely need to call these yourself, but both are exported so you can inspect or reuse them:

import {
  applyPaletteToConfig,
  applyPaletteToResolvedConfig,
  resolveColorValue,
} from 'postext';
 
const flat = applyPaletteToConfig(config);
// Every ColorValue with a paletteId in the raw config now carries the
// palette entry's hex/model (a design colour keeps its paletteId).
 
// `applyPaletteToResolvedConfig` is typically handled by buildDocument; use it
// directly if you build a ResolvedConfig yourself and want the palette applied.

resolveColorValue(value, palette, fallback) is the single-value variant, handy when you are composing configs imperatively and need to resolve one color at a time.

#Editing the palette

A colour whose paletteId names no entry prints its stored hex / model, which may be older than the colour the entry gave it. So before removing an entry, rewrite every ColorValue linked to it as a plain colour holding the entry's current value. The Sandbox's Palette section (Design → Colours) does this when you delete an entry, wherever the colour sits (designs and callout labels included), and its confirmation lists every setting that uses the entry: by name, or by its path in the configuration (header.elements[2].color).

#HTML Viewer

The htmlViewer property controls how the HTML backend lays out pages on screen. It only applies when you render with renderToHtml / renderToHtmlIndexed; the canvas and PDF paths ignore it entirely — they consume the configured page.width, page.height, and page.dpi directly.

interface HtmlViewerConfig {
  maxCharsPerLine?: number;     // Target column width, in characters of the body font.
  columnGap?: number;            // Horizontal gap between columns in multi-column mode (px).
  optimalLineBreaking?: boolean; // Use Knuth–Plass inside the HTML viewer instead of greedy.
  overrides?: HtmlViewerOverrides; // Screen-only partial config merged over the document config.
}
 
type HtmlViewerOverrides = Omit<PostextConfig, 'htmlViewer'>;
PropertyTypeDefaultDescription
maxCharsPerLinenumber70Target measure for each rendered column, expressed in characters of the body font. The viewport samples a representative prose string at that length to derive the actual pixel width — so the result adapts to any proportional font and font-size combination.
columnGapnumber50Horizontal gap, in CSS pixels, between columns when the viewer is in multi-column mode. Ignored in single-column mode.
optimalLineBreakingbooleantrueBreak the lines of the HTML viewer with Knuth–Plass, the same optimal breaks the canvas and the PDF make: the screen edition gives up nothing in quality to the printed one. With true the viewer follows bodyText.optimalLineBreaking, so a document that sets its text line by line keeps that on screen. Set it to false to fill each line before the next, which is faster on a very long book. A configuration stored under configVersion 21 or older that does not set it reads as false, as it was laid out then.
overridesHtmlViewerOverrides—A partial document config that applies on screen only. The HTML viewer merges it over the document config before laying out (applyHtmlViewerOverrides); canvas and PDF ignore it. Objects merge recursively; a levels array (headings, lists, contents) merges entry by entry on level; every other array — a design slot's elements, calloutStyles, colorPalette… — replaces the base array wholesale. Typical use: a chapter opener without the print bands, or a part page whose title wraps against the number instead of a fixed trim-box width. The sandbox edits it as JSON.
const config: PostextConfig = {
  headings: { levels: [{ level: 1, span: 'page', breakBefore: { enabled: true } }] },
  htmlViewer: {
    // On screen, chapters flow on without the page-span opener.
    overrides: { headings: { levels: [{ level: 1, span: 'column', breakBefore: { enabled: false } }] } },
  },
};

Resolver and stripper follow the same pattern as the other sections:

import {
  DEFAULT_HTML_VIEWER_CONFIG,
  resolveHtmlViewerConfig,
  stripHtmlViewerDefaults,
} from 'postext';
 
const resolved = resolveHtmlViewerConfig(config.htmlViewer);
// => { maxCharsPerLine: 70, columnGap: 50, optimalLineBreaking: true }
 
const minimal = stripHtmlViewerDefaults(config.htmlViewer);
// => undefined when everything matches the defaults

See Integrating the HTML viewer below for an end-to-end example.

#Canvas viewer

The canvasViewer property sets the space between the pages in the Sandbox's Canvas tab (since postext 1.43). It belongs to the viewer, not to the book: the values are screen pixels at any zoom, and changing them moves the pages on screen without laying the book out again, so the pagination, the saved layouts and the PDF stay as they were. The PDF, the HTML viewer and the other outputs ignore it. A book whose pictures run across a spread sets pageGap: 0.

interface CanvasViewerConfig {
  pageGap?: number; // Space between the two pages of a pair (px).
  rowGap?: number;  // Space between one row of pages and the next (px).
}
PropertyTypeDefaultDescription
pageGapnumber24Space, in screen pixels, between the left and right page of a pair in the double-page view. A whole number from 0 to 200. With 0 the two pages touch and the Canvas draws no shadow or rounded corner at the joint, so a picture or a design across the spread reads as one. The single-page view has no pairs.
rowGapnumber24Space, in screen pixels, between one row of pages and the next, in both views. A whole number from 0 to 200.
const config: PostextConfig = {
  // A picture runs across the spread: show the two pages joined.
  canvasViewer: { pageGap: 0 },
};
import {
  DEFAULT_CANVAS_VIEWER_CONFIG,
  resolveCanvasViewerConfig,
  stripCanvasViewerDefaults,
} from 'postext';
 
resolveCanvasViewerConfig(config.canvasViewer);
// => { pageGap: 0, rowGap: 24 }
 
stripCanvasViewerDefaults({ pageGap: 24, rowGap: 24 });
// => undefined when everything matches the defaults

A value that is not a whole number from 0 to 200 is read as the nearest such number, or as 24 when it is not a number, and reported as an unknown setting value (canvasViewer.pageGap). The Sandbox has both fields in Design › Export › Canvas (page spacing).

#PDF generation (config)

The pdfGeneration property controls how the PDF backend emits the final document. These settings are consumed by the postext-pdf package at export time; the canvas and HTML viewers ignore them. forms is the exception: the canvas reads it too, so its form fields match the PDF's.

buildDocument carries them in the VDT, as doc.config.pdfGeneration, and renderToPdf takes each setting from the first place that gives it:

  1. its own options (outlines, accessible, colorSpace, baselineGrid, forms);
  2. the pdfGeneration of the first document it renders (in a book, the first chapter's settings apply to the whole file);
  3. the defaults: bookmarks and tagging on, RGB colour.

So renderToPdf(doc, { fontProvider }) follows the config, and an option passed to renderToPdf wins for that setting only. forceColorSpace and colorSpace together stand for the colorSpace option: the config's colorSpace applies while forceColorSpace is on, and the PDF is RGB while it is off. Earlier releases of postext-pdf read the options only; a config that sets pdfGeneration now changes the PDF of a caller that passes no options.

type PdfColorSpace = 'rgb' | 'cmyk' | 'grayscale';
 
interface PdfGenerationConfig {
  outlines?: boolean;          // Emit PDF bookmarks from the heading tree.
  forceColorSpace?: boolean;   // Convert every colour to `colorSpace`.
  colorSpace?: PdfColorSpace;  // Target space used when `forceColorSpace` is true.
  accessible?: boolean;        // Tagged, PDF/UA-oriented output (structure tree, alt text, language).
  baselineGrid?: boolean;      // Draw the `page.baselineGrid` grid in the PDF as well.
  forms?: PdfFormsConfig;      // Form fields: currency, separators, face.
}
PropertyTypeDefaultDescription
outlinesbooleantrueEmit PDF outlines (bookmarks) from the heading hierarchy so readers can jump directly to any heading from the sidebar of a PDF viewer. Turn off for documents where the heading tree is meaningless (e.g. single-page posters).
forceColorSpacebooleanfalseWhen true, every colour in the rendered PDF is converted to colorSpace at export time. Leave off for screen-first PDFs where input colours are already in the desired space; turn on to guarantee a single colour space across mixed sources.
colorSpace'rgb' | 'cmyk' | 'grayscale''cmyk'Target colour space used when forceColorSpace is on. Use 'cmyk' for offset printing, 'rgb' for screen-only PDFs, and 'grayscale' for black-and-white print proofs. Has no effect when forceColorSpace is false. CMYK is separated through the output profile of print (FOGRA39 by default) with its black handling, and RGB pictures are converted too; a PDF/X standard there writes CMYK whatever this says.
accessiblebooleantrueEmit an accessible, tagged PDF oriented to PDF/UA-1: a logical structure tree in reading order (headings that never skip a level, paragraphs, lists, block quotes, callouts, tables with header cells, figures with their alt text and captions, formulas, clickable refs as links, the contents of a :::toc as one TOC with a TOCI per row: the row's number as a Lbl, its title and page as a Reference holding the link), the document title and language (the top-level locale), the PDF/UA identification in the XMP metadata, and every decorative mark (page background, rules, baseline grid, running headers and footers, cut marks, repeated table headers, the repeated title and continuation marker of a split callout) flagged as an artifact so screen readers skip it. A figure without altText falls back to its caption, then to its label. A floated figure or table is read right after the text that first cites it, or the text before its ::resource line, and a floated box after the text before its fence, even when the float is placed on a later page; a list or the contents that go on past a float stay one element, and a list inside a floated or fixed box (placement: 'fixed') is one list. Turn off only for print masters where the extra structure is unwanted.
baselineGridbooleantrueDraws the baseline grid in the PDF while page.baselineGrid is on. On by default, as before; false keeps the grid a guide for checking the page on screen, out of the PDF, while the canvas and the HTML viewer keep showing it. In the Sandbox it is Baseline grid in the PDF, in the PDF section.
formsPdfFormsConfigundefinedHow form fields write numbers and the face they show values in: currency (default €), currencyBefore (default true), separatorStyle (0 to 3; from the document language when unset) and font ('chip', the default, 'helvetica' or { family, weight?, style? }). The forms option of renderToPdf and of the canvas wins field by field. Output only: it changes no layout. See Form fields.
pdfGeneration: {
  outlines: true,
  accessible: true,
  forceColorSpace: true,
  colorSpace: 'cmyk',
}

Resolver and stripper match the other sections:

import {
  DEFAULT_PDF_GENERATION_CONFIG,
  resolvePdfGenerationConfig,
  stripPdfGenerationDefaults,
} from 'postext';
 
const resolved = resolvePdfGenerationConfig(config.pdfGeneration);
// => { outlines: true, forceColorSpace: false, colorSpace: 'cmyk', accessible: true }
 
const minimal  = stripPdfGenerationDefaults(config.pdfGeneration);
// => undefined when everything matches the defaults

See Generating PDFs below for the end-to-end export recipe.

The print property says how a book goes to press: the PDF/X standard of the file, the output profile its CMYK is separated with, how black prints, and the thresholds of the preflight. Layout ignores it, so changing it never moves a line. Three things read it: postext-pdf when it writes the file, preflightDocument when it checks a laid-out document, and the print preview of the canvas and Folio viewers.

type PdfXStandard = 'none' | 'pdfx1a' | 'pdfx4';
 
interface PrintConfig {
  standard?: PdfXStandard;                 // 'none': an ordinary PDF.
  outputProfile?: string;                  // A catalogue id ('fogra39', 'fogra51'…) or 'custom'.
  customProfile?: CustomOutputProfile;     // An uploaded .icc file.
  renderingIntent?: 'relative' | 'perceptual';
  blackPointCompensation?: boolean;
  convertImages?: boolean;                 // Separate RGB pictures (PDF/X-1a always does).
  inkLimit?: number;                       // Total area coverage, percent.
  black?: PrintBlackConfig;
  preflight?: PrintPreflightConfig;
  inks?: PrintInk[];                       // The ink table: renames, aliases, process.
  plates?: PrintPlatesConfig;              // The plates the job prints on: two-ink printing.
  imageColor?: PrintImageColorConfig;      // How pictures are read: profiles, greyscale.
}
 
interface CustomOutputProfile {
  name: string;           // Its description, or the file name.
  fileId: string;         // The stored .icc file.
  registryName?: string;  // The condition's ICC registry name (FOGRA51…), else 'Custom'.
  inkLimit?: number;
}
PropertyTypeDefaultDescription
standard'none' | 'pdfx1a' | 'pdfx4''none'The PDF/X flavour of the file. 'pdfx1a' writes PDF/X-1a:2003: CMYK and grey only, no transparency, accepted by every printer. 'pdfx4' writes PDF/X-4: transparency and colour management kept, for current workflows. Either one separates every colour through the output profile, whatever pdfGeneration.colorSpace says.
outputProfilestring'fogra39'The printing condition CMYK is separated for: an id of the profile catalogue, or 'custom' for customProfile. An id the catalogue lacks, or 'custom' without a file, falls back to the default and gets a configuration warning.
customProfileCustomOutputProfilenoneA CMYK output profile you supply, the one your printer gives you (ECI's PSOcoated_v3.icc, for instance). Its bytes are stored out of band like a font; renderToPdf takes them as its outputProfile option. registryName is written as the output intent's condition identifier.
renderingIntent'relative' | 'perceptual''relative'Relative colorimetric keeps the colours the press can print exact and clips the rest to the nearest printable one; perceptual compresses the whole range so out-of-gamut colours keep their relations.
blackPointCompensationbooleantrueWith the relative intent, map the screen's black onto the darkest black the press prints, so the darkest tones keep their detail instead of filling in.
convertImagesbooleantrueSeparate RGB pictures into CMYK with the profile. PDF/X-1a always does. In PDF/X-4, false keeps them RGB, tagged sRGB through the pages' /DefaultRGB, for the printer's RIP to convert. CMYK and grey JPEGs are always embedded as they are.
inkLimitnumberthe profile'sThe highest total of C+M+Y+K, in percent, the preflight accepts. Defaults to the limit the profile separates to (300 % for most offset conditions, 230 % for IFRA26 newsprint).
blackPrintBlackConfigsee BlackK-only greys, overprint and rich black.
preflightPrintPreflightConfigsee PreflightWhat the preflight checks and its thresholds.
print: {
  standard: 'pdfx4',
  outputProfile: 'fogra51',
  black: { richBlackColor: { c: 60, m: 40, y: 40, k: 100 } },
  preflight: { minImageResolution: 300, safeZone: { value: 5, unit: 'mm' } },
}

#Output profiles

postext ships these CMYK output profiles in its icc/ folder (postext/icc/<id>.icc on any npm CDN, and /icc/<id>.icc on postext.dev). All of them are free of known copyright restrictions (CC0): the FOGRA, GRACoL, SWOP and newspaper profiles of colord, generated from the characterization data of each condition, and FOGRA51 and FOGRA52, built by postext with ArgyllCMS from Fogra's own data. ECI's profiles (ISO Coated v2, PSO Coated v3, PSO Uncoated v3) describe the same conditions but may not be redistributed; upload them as a custom profile if your printer asks for them.

IdConditionRegistry nameInk limit
fogra39Offset, coated paper (ISO Coated v2 condition)FOGRA39300 %
fogra51Offset, premium coated (PSO Coated v3 condition)FOGRA51300 %
fogra52Offset, wood-free uncoated (PSO Uncoated v3 condition)FOGRA52300 %
fogra47Offset, uncoated white (PSO Uncoated ISO 12647)FOGRA47300 %
fogra29Offset, uncoated whiteFOGRA29300 %
fogra30Offset, uncoated yellowishFOGRA30340 %
fogra27Offset, coated (ISO 12647-2:1996)FOGRA27300 %
fogra28Heatset web offset, glossy LWCFOGRA28300 %
fogra45Heatset web offset, improved LWCFOGRA45300 %
fogra40Heatset web offset, SC paperFOGRA40340 %
gracol2006GRACoL 2006, grade 1 coatedCGATS TR 006300 %
swop3SWOP 2006, grade 3 coatedCGATS TR 003300 %
swop5SWOP 2006, grade 5 coatedCGATS TR 005300 %
ifra26Coldset newsprint (ISO 12647-3)IFRA26230 %
snap2007SNAP 2007 newsprintCGATS TR 002320 %

renderToPdf reads the profile's bytes from its outputProfile option; without them it fetches the catalogue file from profileBaseUrl (by default https://cdn.jsdelivr.net/npm/postext/icc/). A PDF/X render whose profile cannot be loaded fails; a plain CMYK render falls back to the textbook formula with an outputProfileUnavailable warning.

import { readFile } from 'node:fs/promises';
import { renderToPdf } from 'postext-pdf';
 
const pdf = await renderToPdf(doc, {
  fontProvider,
  print: { standard: 'pdfx1a', outputProfile: 'fogra39' },
  outputProfile: await readFile('node_modules/postext/icc/fogra39.icc'),
});

#PDF/X-1a and PDF/X-4

Both standards write:

  • the output intent (GTS_PDFX) naming the printing condition and embedding the destination profile;
  • the identification in the Info dictionary (GTS_PDFXVersion, /Trapped /False, the title and dates) and in the XMP metadata (pdfxid:GTSPDFXVersion, the document and version ids), merged with the PDF/UA identification when the file is tagged;
  • a TrimBox and a BleedBox on every page (the whole page when there are no cut lines);
  • the trailer /ID;
  • every colour in DeviceCMYK (or grey) through the profile, and the crop marks in registration colour;
  • no link annotations: a file for the press carries none inside its bleed box, so the links of the screen PDF are left out (bookmarks stay).

PDF/X-1a:2003 is PDF 1.4 without object streams and has no transparency: a translucent colour is set as it would print over the paper, a picture's alpha is flattened over white, and the debug page negative is left out (with a pageNegativeIgnored warning). PDF/X-4 is PDF 1.6: transparency stays, each page gets a transparency group blending in CMYK, and RGB pictures kept by convertImages: false are tagged sRGB through /DefaultRGB.

A PDF print master (svg.pdfFileId) is embedded as it is, so its colours, fonts and transparency are its own; the preflight reports what it brings in.

#Black

interface PrintBlackConfig {
  kOnlyNeutrals?: boolean;      // Greys and black in black ink only.
  overprint?: boolean;          // 100 % K overprints.
  richBlack?: boolean;          // Large black areas in rich black.
  richBlackColor?: CmykPercent; // { c, m, y, k } in percent.
  richBlackMinSize?: Dimension; // The smaller side an area needs.
}
PropertyTypeDefaultDescription
kOnlyNeutralsbooleantrueA neutral colour (#000000, #808080…) prints with black ink alone, its K picked so the lightness matches, never as a four-colour grey that shifts with registration. Pictures keep the profile's own black generation.
overprintbooleantrueWhatever paints in 100 % K alone (black text, rules, strokes, small black shapes) overprints (op/OP with OPM 1), so a plate shifting on press never opens a white edge round it. Everything else knocks out; pictures and shadings never overprint.
richBlackbooleantrueA black fill whose smaller side reaches richBlackMinSize (a background, a band, a box) prints in richBlackColor and knocks out, so it looks deep instead of dark grey. Text never turns rich.
richBlackColorCmykPercent{ c: 60, m: 40, y: 40, k: 100 }The rich-black recipe, in percent. Keep its total under the ink limit; the preflight checks it.
richBlackMinSizeDimension6mmThe smaller side a black area needs to print in rich black.

A canvas page can be painted as it will print. createPrintPreview(transform, print, { paper, dpi, grayscale }) builds the soft proof of a setup: every pixel is separated through the profile (K-only neutrals, as in the PDF) and shown back on screen, on the paper's own white when paper is true; black areas large enough for rich black show as rich black. With grayscale, the proof is a grayscale print — a PDF forced to grayscale prints each colour's luma in black ink alone, without rich black. Hand it to renderPageToCanvas as printPreview. For a working view, not a proof, guides adds the trim, bleed and safe-zone lines and marksFor outlines areas of a page (the preflight's rects); the Sandbox leaves both out, so its preview shows only the print. postext-folio takes the same object as printPreview; with paper: true, give the book a neutral paper shade meanwhile (folio.paper.shade), or the paper is tinted twice.

import { createPrintPreview, renderPageToCanvas } from 'postext';
 
const preview = createPrintPreview(transform, print, { paper: true, dpi: doc.config.page.dpi });
renderPageToCanvas(page, doc, canvas, {
  printPreview: { ...preview, guides: { safeZonePx: 59 }, marksFor: () => issues.map((i) => i.rect!).filter(Boolean) },
});

#Colour engine

The colour management postext uses is exported for your own tools. It reads ICC v2 and v4 profiles (matrix/TRC and the mft1, mft2, mAB, mBA lookup tables) in plain TypeScript, with no WebAssembly.

  • parseIccProfile(bytes) reads a profile; deviceChannels(profile) gives its channel count.
  • outputTransform(profile, { intent, blackPointCompensation, preserveNeutrals }) returns fromRgb(r, g, b) (sRGB 0..1 → CMYK 0..1), toLab(cmyk, paper?) and proof(cmyk, paper?) (CMYK → screen sRGB).
  • cmykToLab, labToCmyk, srgbToLab, labToSrgb, deltaE and totalAreaCoverage are the single conversions; buildRgbLut / sampleRgbLut make and read dense lookups for pixel work.
  • OUTPUT_PROFILES, outputProfileInfo(id) and loadOutputProfile(id, baseUrl?) give the catalogue; srgbProfileBytes() writes the sRGB profile that PDF/X-4 tags RGB with; authoredCmykColors(config) lists the colours a config authored in CMYK.

The resolver and stripper match the other sections: resolvePrintConfig, stripPrintDefaults and profileInkLimit(config) (the limit of the profile a config names, before any inkLimit override), with DEFAULT_PRINT_CONFIG, DEFAULT_PRINT_BLACK_CONFIG, DEFAULT_PRINT_PREFLIGHT_CONFIG and DEFAULT_RICH_BLACK.

#Contrast check (config)

The contrast property sets the check that says whether the text of a book can be read: every text colour against the ground it is set on. Layout ignores it, so changing it never moves a line. contrastDocument reads it when it checks a laid-out document, the Sandbox lists the findings in Checks and shows the ratio beside each colour field, and postext check prints them.

interface ContrastConfig {
  enabled?: boolean;
  level?: 'AA' | 'AAA';
  mode?: 'auto' | 'screen' | 'print' | 'both';
  reversedText?: {
    enabled?: boolean;
    minSize?: Dimension;
    minFineSize?: Dimension;
    lightWeight?: number;
  };
  allow?: { fg?: string; bg?: string; style?: string; reason: string }[];
}
PropertyTypeDefaultDescription
enabledbooleantrueRun the check.
level'AA' | 'AAA''AA'The WCAG 2 level the ratios are held to. See Thresholds.
modestring'auto'The rendition read: 'screen', 'print', 'both', or 'auto', which reads the screen always and print as well for a book set up for print (a PDF/X standard in print.standard, a CMYK PDF in pdfGeneration, or crop marks in page.cutLines).
reversedText.enabledbooleantrueReport reversed text in the print check.
reversedText.minSizeDimension8ptReversed text under this size is reported.
reversedText.minFineSizeDimension12ptThe same for italics and light weights, whose strokes are thinner.
reversedText.lightWeightnumber300A weight at or under this one counts as light.
allowContrastAllowEntry[][]Colour pairs the check accepts, each with its reason: by the text colour (fg) and the ground (bg), by the style the text is set in, or both. See Accepted pairs.

A level or a mode written any other way reads as the default and is reported as an unknown setting value (see Configuration warnings).

#Accepted pairs

A port keeps the palette of its source, and some of its pairs fall under the threshold: a pale tint behind a box's text, a brand colour in a running head. allow accepts them without turning the check off (since postext 1.52). An entry names the text colour fg and the ground bg (hex, as the configuration writes them or as they are painted), or a style: the id of a box style (calloutStyles, or the style of a composed page's frame), a paragraph style, a heading style, a chip style or a figure label style. Every field an entry gives has to match, so { style: 'note', fg: '#7a8a99' } accepts that grey only inside note boxes. An entry that gives none of the three matches nothing.

contrast: {
  allow: [
    { fg: '#b7820f', bg: '#ffffff', reason: "The publisher's ochre for running heads" },
    { style: 'margin-note', reason: 'The source sets its margin notes in a light grey' },
  ],
}

An accepted pair is still reported: each finding it matches carries accepted (the entry's reason, with its fg, bg and style), and the accepted findings come after the others. The Sandbox lists them under Accepted contrast pairs in Checks, with the reason, and does not count them; postext check prints them as notes, which --strict does not fail on. The same colours set outside what the entry names stay a warning.

#Thresholds

The ratio a text must reach follows its size and weight, as in WCAG 2.

LevelTextLarge text
AA4.5:13:1
AAA7:14.5:1

Large text is 18 pt and over, or 14 pt and over at a weight of 700 or more. The sizes are the printed ones, in points. A superscript or a subscript is judged at the size of the text it belongs to.

#Screen and print

Postext sets the same pages for a screen and for a press, and a colour does not read the same on both.

  • Screen is the WCAG 2 contrast ratio of the sRGB colours, (L1 + 0.05) / (L2 + 0.05) over their relative luminances: what the canvas, the HTML viewer, an EPUB and an RGB PDF show.
  • Print is the same formula over the luminance each colour has on paper. The colour is separated through the job's output profile (one authored in CMYK keeps its values), the separation is read back through the profile, and its luminance is taken relative to the bare paper, which is the white of a printed page as the display's white is the white of a screen. Ink is never a perfect black: solid black on white comes to about 14:1 on coated paper (FOGRA39, FOGRA51), 8:1 on uncoated paper (FOGRA47, FOGRA52) and 5:1 on newsprint (IFRA26, SNAP), where a screen gives 21:1. A grey that passes on screen can fail on paper: #767676 on white is 4.54:1 on screen and about 3.3:1 on coated paper.

The print ratio needs the transform of the output profile (options.transform, built with outputTransform). Without it only the reversed text is checked for print.

#Reversed text

Light text knocked out of an inked ground fills in on press when it is small or its strokes are thin: the ink of the ground spreads into the letters, and a ground built of several inks also depends on the plates staying in register. The ratio does not show it, since white on dark blue is over 10:1. The print check reports such text on its own (reversedText) when it is under minSize, or under minFineSize while italic or at a weight of lightWeight or less. Each finding says how many of the four inks the ground is built of.

#What is read

The check reads the lines of every block with their inline colours (bold, italic, references, chips), list markers, drop caps, captions, notes and table cells, and the text of design slots: running heads, openers, heading designs, box titles. The ground is the topmost fill under the text: a design box, a callout, a caption bar, a table cell, a chip, or else the page colour (page.backgroundColor, or the paper a part's palette gives its pages). A translucent colour is blended with what is under it. Text over a picture is skipped, since its ground is not one colour, and so are comic lettering, ruby readings and formulas. The words of a figure's labels are read on their plate, or inside their halo when they have one; labels bare on the picture are skipped like any text over a picture.

On a composed page the check follows the order the page is painted in: the frames by layer, with the template's decoration at layer 0. Frame text stands on its frame's own box when the frame's style paints one, else on the decoration box under it (text over a picture in the decoration is skipped, as over any picture), else on the page colour, so white lettering on a coloured tab of the decoration is measured against that tab. A turned or scaled frame is put on the sheet before its ground is read, and the decoration's own text is checked the same way. Since postext 1.37.

#Running the check

contrastDocument(doc, options) returns the findings of a laid-out document, lowest ratio first. Each one has the book-absolute pageIndex, the rect on the sheet (page px) and the source range of its first occurrence, the two colours as painted (color, background), the smallest sizePt it is set at with its weight and italic, a role ('body', 'heading', 'caption', 'table', 'runningHead', 'design', 'chip', 'marker' or 'label', the words of a figure's labels), the first run's text and the count of runs set that way. A pair is reported once per threshold, however many lines use it.

  • lowContrast adds level, large, required, the ratio in each rendition checked (screen, print) and failing, the renditions under required.
  • reversedText adds reasons ('small', 'italic', 'light'), minimumPt and inks.

The options are contrast (the resolved settings, when they are not the document's), media (the renditions, whatever mode says) and transform.

import { contrastDocument, outputTransform, parseIccProfile } from 'postext';
 
const transform = outputTransform(parseIccProfile(fogra51Bytes));
for (const issue of contrastDocument(doc, { transform })) {
  if (issue.kind === 'lowContrast') {
    console.log(`${issue.color} on ${issue.background}: ${issue.screen}:1, ${issue.level} asks for ${issue.required}:1`);
  }
}

contrastPairs(doc, options) returns every text and ground pair the document sets, passing or not, with its screen ratio, its print ratio when the transform is given, the ratio required and the colours as the configuration writes them (textColor, groundColor): what a design tool shows beside a colour field. It runs whatever enabled says.

The measures are exported for your own tools:

  • contrastRatio(a, b) and relativeLuminance(color) give the WCAG 2 ratio and luminance of sRGB colours.
  • isLargeText(sizePt, weight) and contrastThreshold(level, large) give the threshold of a size and weight.
  • blendColors(top, under) gives a translucent colour over another, as #rrggbb.
  • printContrastRatio(a, b, context), printLuminance(color, context) and printSeparation(color, context) give the same on paper. The context holds the transform and, as authored, the result of authoredCmykColors(config).
  • contrastMedia(doc.config, contrast) gives the renditions mode resolves to for a document.

The resolver and stripper match the other sections: resolveContrastConfig and stripContrastDefaults, with DEFAULT_CONTRAST_CONFIG, DEFAULT_CONTRAST_REVERSED_TEXT_CONFIG, CONTRAST_LEVELS and CONTRAST_MODES.

#Content check (config)

The checks property holds the checks that read the configuration itself. It has one today, contentInConfig, which warns when a design keeps the book's text. A running head, a heading design, a part page and a contents part row are form: they hold placeholders ({chapterTitle}, {titleText}, {number}) and at most a word or two of their own, such as Chapter before {chapterNumber}. Text that is part of the book belongs in the Markdown, where the contents, the search, translations, the tagged PDF and the EPUB see it. Layout ignores the check, so changing it never moves a line.

interface ChecksConfig {
  contentInConfig?: {
    enabled?: boolean;
    allow?: string[];
    maxWords?: number;
    maxChars?: number;
  };
}
PropertyTypeDefaultDescription
contentInConfig.enabledbooleantrueRun the check.
contentInConfig.allowstring[][]Phrases a design may repeat at any length: the book's title, the publisher's name. They are compared without case, spacing or the punctuation around words, and a phrase found inside a longer text is taken out before the rest is counted.
contentInConfig.maxWordsnumber2Most words a design text may hold beyond its placeholders.
contentInConfig.maxCharsnumber24Most letters and digits a design text may hold beyond its placeholders. A Chinese, Japanese, Korean or Thai character counts as three, so about eight of them pass.

#How a design text is read

  • Its literal text is its content with every placeholder taken out ({name}, {attr.key}, {firstMark.key}), the {{ and }} escapes read as braces and \n as a line break.
  • A text with no letter or digit (a row of leader dots, an ornament, a ·) is never content.
  • A word is what stands between spaces and holds a letter or a digit: a lone · or | is no word, and an address such as postext.dev is one.
  • The phrases of allow are taken out first, and so are the title, subtitle, author and publisher of the document's metadata (its front matter), which a running head often repeats.
  • What is left is content when it has more than maxWords words or more than maxChars letters and digits.

Every design slot is read: header, footer, each heading level's advancedDesign.slot, each heading style's advancedDesign.slot, header and footer, parts.design, parts.versoDesign, toc.parts.design, and the same under htmlViewer.overrides. configDesignSlots(config) lists them with their paths, and designTextLiteral(content) returns the literal text of a template.

#The warning

collectConfigWarnings (and VDTDocument.configWarnings) gives one contentInConfig warning per setting that holds content: a heading style (its id in ownerId), a heading level, the header, a part design. path names the setting, count the design texts at fault, chars their letters and digits, elements the path of each (the first 20) and value the start of the first text (40 characters at most). Pass the document's metadata as the second argument to allow its title and author; a build does it on its own.

import { collectConfigWarnings } from 'postext';
 
collectConfigWarnings(config, { metadata: { title: 'A Year of Weather' } });
// [{ kind: 'contentInConfig', path: 'headingStyles[3]', ownerId: 'lesson-4',
//    value: 'Look at the picture and answer the questi…', used: '',
//    count: 30, chars: 1017, elements: ['headingStyles[3].header.elements[2]', …] }]

Fix: move the text into the Markdown, as a heading, a callout or a paragraph of the chapter it belongs to, and keep only placeholders in the design. A value that changes per chapter can travel on the heading line and be read with {attr.key}: # Maps {kicker="Lesson 4"} and {attr.kicker} in the design. A phrase that is form, such as the publisher's name in a running head, goes in allow.

The Sandbox lists the warning in Checks and sets the check under Design → Advanced → Content in the configuration; postext check prints it.

#Folio viewer (config)

The folio property sets how the Folio viewer (postext-folio) presents the printed book in 3D: the angle of the view, the paper, the binding, the surface the book lies on and the light. Layout ignores it, and so do the canvas, HTML and PDF output. buildDocument carries the resolved settings in the VDT as doc.config.folio when the config sets any, so a document without them keeps its layout hash.

interface FolioConfig {
  tilt?: number;                  // Degrees from straight above, 0–70.
  yaw?: number;                   // Degrees round the book, −180–180.
  paper?: {
    type?: 'uncoated' | 'bookWove' | 'coatedMatte' | 'coatedSilk' | 'coatedGloss'
         | 'bible' | 'newsprint' | 'cardStock' | 'board';
    grammage?: number;            // g/m²
    bulk?: number;                // cm³/g; caliper µm = grammage × bulk
    finish?: 'auto' | 'uncoated' | 'matte' | 'silk' | 'gloss';
    texture?: 'auto' | 'smooth' | 'vellum' | 'wove' | 'laid' | 'linen' | 'felt';
    textureStrength?: number;     // 0–2
    shade?: ColorValue;
    showThrough?: boolean;
  };
  binding?: {
    type?: 'hardcover' | 'paperback' | 'sewn' | 'layflat' | 'saddleStitch' | 'folded';
    cover?: 'case' | 'pages';
    coverMaterial?: 'auto' | 'cloth' | 'paper' | 'leather';
    coverColor?: ColorValue;
    spineImage?: string;          // resource id
  };
  surface?: {
    type?: 'oak' | 'walnut' | 'linen' | 'felt' | 'leather' | 'marble' | 'plain' | 'none';
    color?: ColorValue;
  };
  lighting?: {
    environment?: 'studio' | 'daylight' | 'lamp' | 'overcast' | 'night';
    intensity?: number;           // 0.25–2
    shadows?: boolean;
  };
}
PropertyTypeDefaultDescription
tiltnumber22Angle of the view away from straight above, in degrees, clamped to 0–70. At 0 the open book is seen flat from overhead; a larger angle brings the foot of the pages closer and shows the depth of the book block.
yawnumber0How far the view is turned round the book, in degrees, brought into −180–180. At 0 the book is seen from the foot of its pages; a positive angle brings the eye round to its right, a negative one to its left. With tilt it is the view the viewer opens on and the one resetView() eases back to.
paper.typeFolioPaperType'uncoated'; 'newsprint' on a newspaper trimThe paper stock. It supplies the defaults of the five fields below (see the table of stocks). cardStock is cover card; board is rigid board, as in a board book, and its leaves turn without bending.
paper.grammagenumberthe stock'sWeight in grams per square meter, 20–2500. Heavier paper is thicker, stiffer and more opaque: a leaf bends in a wider curve and shows less of the reverse.
paper.bulknumberthe stock'sThickness per unit of weight, in cm³/g, 0.5–3. The caliper of a sheet in micrometers is grammage × bulk, and the thickness of the book block follows from it and the page count.
paper.finishFolioPaperFinish'auto'Uncoated (fibre, no sheen), or coated and calendered to matte, silk (a soft sheen) or gloss. A gloss page mirrors the leaf turning over it in Folio. 'auto' takes the stock's.
paper.textureFolioPaperTexture'auto'The relief of the surface: smooth (calendered), vellum (a fine tooth), wove (the even texture of most book papers, formed on a woven wire), laid (close laid lines crossed by wider chain lines, left by a dandy roll), linen (an embossed cross-weave), felt (irregular felt marks). 'auto' takes the stock's.
paper.textureStrengthnumber1How strongly the texture shows in the light, 0–2.
paper.shadeColorValuethe stock'sThe colour of the paper before printing (white, natural, cream). The pages are printed on it.
paper.showThroughbooleantrueThe reverse of a page shows faintly through thin paper. After bible paper, newsprint shows it most: its ink soaks into the sheet.
binding.typeFolioBindingType'hardcover'; 'folded' on a newspaper trimhardcover: case bound, boards slightly larger than the pages. paperback: perfect bound (milled and glued), opens less flat. sewn: a softcover with sewn sections. layflat: opens flat, with no dip at the gutter. saddleStitch: folded sheets stapled through the fold, as a magazine or a booklet; no flat spine. folded (since postext 1.18): a newspaper, sheets folded once and laid one inside the other with nothing holding them; no staples, no spine and no cover board, and the first page is the front. A :::paper run with a shade prints a section, such as the business pages, on salmon newsprint.
binding.coverFolioCoverSource'case'The covers. 'case' draws a case round the pages. 'pages' takes the book's first page as the front board and its last page, when it is a verso, as the back board: the book lies closed until the cover is turned, the boards turn stiff (on a saddle stitch the cover is a sheet a little heavier than the pages and turns as they do), and no case is drawn.
binding.coverMaterialFolioCoverMaterial'auto''auto' is cloth on a hardcover and card ('paper') on the other bindings.
binding.coverColorColorValuedark blue (#2c3e57)The colour of the cover material.
binding.spineImagestringnoneThe id of a bitmap or SVG resource printed on the spine: the spine as seen with the book standing, head up and the front cover to the right. It is fitted to cover the spine, centred. Ignored on a saddle stitch and on a folded binding.
surface.typeFolioSurfaceType'oak'What the book lies on. 'none' leaves the host's background.
surface.colorColorValuenoneTints the surface; on 'plain' it is the surface's colour.
lighting.environmentFolioEnvironment'studio'The surroundings reflected by coated and gloss paper, paired with the key light that casts the shadows.
lighting.intensitynumber1Exposure, 0.25–2.
lighting.shadowsbooleantrueShadows cast by the key light.

The stocks and the values they supply (FOLIO_PAPER_STOCKS), typical of mill data sheets:

StockGrammageBulkCaliperFinishTextureShade
uncoated (woodfree offset)90 g/m²1.25113 µmuncoatedwove#fcfbf8
bookWove (cream, high bulk)80 g/m²1.6128 µmuncoatedwove#f6efdc
coatedMatte115 g/m²1.0115 µmmattesmooth#fdfdfc
coatedSilk115 g/m²0.9104 µmsilksmooth#ffffff
coatedGloss115 g/m²0.892 µmglosssmooth#ffffff
bible40 g/m²1.144 µmuncoatedvellum#f9f6ee
newsprint48 g/m²1.572 µmuncoatedwove#ebe7dc
cardStock250 g/m²1.2300 µmuncoatedvellum#fbfaf6
board1250 g/m²1.62000 µmsilksmooth#ffffff

A novel on cream book paper, bound as a paperback, on a walnut desk under a reading lamp:

folio: {
  paper: { type: 'bookWove' },
  binding: { type: 'paperback', coverColor: { hex: '#8a2b1f', model: 'hex' } },
  surface: { type: 'walnut' },
  lighting: { environment: 'lamp' },
}

A page on a newspaper trim (page.sizePreset 'broadsheet', 'berliner', 'tabloid' or 'compact') is shown as a newspaper when the config names no stock and no binding: newsprint paper and a folded binding (since postext 1.18). A stock or a binding the config names is kept, so paper: { type: 'uncoated' } prints a tabloid on offset paper. Paper fields set without a stock (a grammage, a shade) apply to the newsprint. The resolver and the stripper take the trim as a second argument, and folioForTrim(folio, sizePreset) writes the two defaults into the config:

resolveFolioConfig({ tilt: 30 }, 'tabloid');
// => { tilt: 30, paper: { type: 'newsprint', grammage: 48, bulk: 1.5, … }, binding: { type: 'folded', coverMaterial: 'paper', … }, … }
 
stripFolioDefaults({ paper: { type: 'newsprint' }, binding: { type: 'folded' } }, 'tabloid');
// => undefined

The colours follow palette links like any other colour of the config (paletteId). Resolver and stripper match the other sections; the stripper drops paper values equal to the chosen stock's:

import { FOLIO_PAPER_STOCKS, DEFAULT_FOLIO_CONFIG, resolveFolioConfig, stripFolioDefaults } from 'postext';
 
resolveFolioConfig({ paper: { type: 'bible' } }).paper;
// => { type: 'bible', grammage: 40, bulk: 1.1, finish: 'uncoated', texture: 'vellum', textureStrength: 1, shade: { hex: '#f9f6ee', … }, showThrough: true }
 
stripFolioDefaults({ paper: { type: 'bible', grammage: 40 } });
// => { paper: { type: 'bible' } }

In the sandbox these settings are the Folio group of the Design panel (Design → Folio → Folio viewer (3D)), and the Folio tab shows them as you change them, without laying the book out again. See A 3D book for the viewer itself, and Document format › :::paper for a run of pages on another stock.

#Debug

The debug property groups two kinds of authoring aids: visual overlays that keep the source text and the rendered layout in sync, and a set of warnings that surface typographic or structural problems in the Sandbox's Checks panel. Neither affects exported output.

PropertyTypeDescription
cursorSyncSyncIndicatorConfigCaret mirrored into the rendered layout — see Visual overlays.
selectionSyncSyncIndicatorConfigSource selection highlighted on the page — see Visual overlays.
looseLineHighlightLooseLineHighlightConfigOverlay on loose justified lines — see Visual overlays.
pageNegative{ enabled: boolean }High-contrast negative of the page — see Visual overlays.
warningsWarningsToggleConfigOne boolean per kind of authoring warning shown in the editor — see Warnings.

#Visual overlays

PropertyTypeDefaultDescription
cursorSync.enabledbooleantrueShows a caret in the rendered layout mirroring the source cursor position.
cursorSync.colorColorValue#2563ebColour of that caret.
selectionSync.enabledbooleantrueHighlights the rendered range matching the source selection.
selectionSync.colorColorValue#fde04780Colour of the highlight — a translucent yellow by default.
looseLineHighlight.enabledbooleanfalsePaints an overlay on justified lines whose word spacing exceeds threshold times the normal space width.
looseLineHighlight.colorColorValue#ff000040Colour of that overlay.
looseLineHighlight.thresholdnumber3Multiplier of the normal space width above which a justified line counts as loose. The looseLines warning uses the same threshold. A justified line whose spaces would stretch past 3× is set ragged, so at the default the overlay and the warning find almost nothing in running text; lower it (1.5 or 2) to see lines that are loose but still justified.
pageNegative.enabledbooleanfalseRenders a high-contrast negative overlay over the page — useful for visually auditing the overall shape of a spread (text density, column balance, whitespace) at a glance, without being distracted by glyph detail.
fitMarks'all' | 'problems' | 'none''problems'Which fit marks the Sandbox canvas draws over composed pages for a reader who has not chosen in the canvas toolbar: every one, only frames that do not fit and unknown looks, or none. The reader's choice wins. Since postext 1.52.
fitMarksMinScalenumber1A frame set at this scale or larger gets no scale badge (0.95 marks only frames under 95 %). Text and pictures are judged apart.

Each SyncIndicatorConfig is { enabled: boolean; color?: ColorValue }. LooseLineHighlightConfig is { enabled: boolean; color?: ColorValue; threshold?: number }. pageNegative is a minimal { enabled: boolean } toggle.

debug: {
  cursorSync: { enabled: true, color: { hex: '#ff0066', model: 'hex' } },
  selectionSync: { enabled: false, color: { hex: '#fde04780', model: 'hex' } },
  looseLineHighlight: { enabled: true, color: { hex: '#ff000040', model: 'hex' }, threshold: 3 },
  pageNegative: { enabled: true },
}

These overlays are drawn by the Sandbox over its Canvas preview. They are not part of the page: renderPage, the HTML output and the PDF never paint them.

#Loose lines in your own canvas

The engine exports the loose-line highlight as two helpers, for a page you paint yourself:

import { buildDocument, renderPageToCanvas, drawLooseLines, findLooseLines } from 'postext';
 
const doc = buildDocument(content, config);
const canvas = document.querySelector('canvas')!;
renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });
drawLooseLines(canvas.getContext('2d')!, doc.pages[0], doc, { threshold: 2.5 });
 
// The same lines as data: a report, an SVG overlay, a count per page.
for (const { ratio, line, block } of findLooseLines(doc, { threshold: 2.5 })) {
  console.log(`page ${block.pageIndex + 1}: ${ratio.toFixed(2)}× — ${line.text}`);
}
  • findLooseLines(doc, { threshold?, pageIndex? }) returns every justified line whose word spacing exceeds threshold, in reading order: { block, line, ratio, x, y, width, height }. ratio is lineWordSpacing(line): the spacing as minWordSpacing and maxWordSpacing bound it (justifiedSpaceLimitRatio when the line holds spaces of another face, else justifiedSpaceRatio), so a line set at the limit with a bold space in it is not reported at a threshold equal to maxWordSpacing. The rectangle, in page pixels, is the band the highlight covers: the block's full width across the line. These are the lines the Sandbox highlights and reports as looseLine in its Checks panel.
  • drawLooseLines(ctx, page, doc, { threshold?, color? }) fills those bands for one page and returns the lines it painted. It draws in page pixels under the context's current transform, so call it right after renderPage or renderPageToCanvas on the same canvas: both leave the context scaled to the page. color is any canvas fill style.
  • Defaults. Both helpers use the default threshold (3) and colour (#ff000040), not the document's debug.looseLineHighlight: that setting belongs to the Sandbox. To follow a configuration, pass resolveDebugConfig(config.debug).looseLineHighlight.threshold and .color.hex.

#Warnings

debug.warnings controls which authoring issues appear in the Sandbox's Checks panel (edited in Design → Advanced → Warnings). Each key is an independent boolean toggle; set one to false to silence that specific warning without disabling the others.

These toggles filter the Sandbox's panel only. The warnings the engine itself records — boxes that overflow their column in doc.warnings; unknown resource ids, directives, embeds and style ids, and irregular table grids in doc.contentWarnings — are there whatever the toggles say, and the renderers report images they paint as placeholders; see Warnings in the document.

interface WarningsToggleConfig {
  missingFont?: boolean;
  looseLines?: boolean;
  headingHierarchy?: boolean;
  consecutiveHeadings?: boolean;
  listAfterHeading?: boolean;
  designIssues?: boolean;
}
PropertyTypeDefaultDescription
missingFontbooleantrueReport when a font referenced by the configuration failed to load in the browser. Catches typos in fontFamily and missing @fontsource/... packages early, before they show up as silent fallback-font substitutions in the rendered output.
looseLinesbooleantrueReport justified lines whose word spacing exceeds debug.looseLineHighlight.threshold. Pairs with the overlay: the warning enumerates them in the panel, the overlay shows them in place.
headingHierarchybooleantrueReport heading levels that skip a rank — e.g. an H1 followed directly by an H3. Structural heading gaps usually indicate either a typo in the heading depth or a misunderstanding of the document's outline.
consecutiveHeadingsbooleanfalseReport when a heading is immediately followed by another heading with no paragraph or list between them. Off by default because stacked headings are legitimate in many templates (title + subtitle, chapter + epigraph); turn on for manuscripts where every heading is supposed to introduce prose.
listAfterHeadingbooleanfalseReport when a list starts immediately after a heading without an introductory paragraph. Off by default because reference material routinely does this; turn on for narrative writing where every list should be framed by prose.
designIssuesbooleantrueReport integrity problems in design slots — page headers, footers, the part opener and the blank verso after it, the part rows of the contents, heading advanced-design slots, and each heading style's design and section running heads. Covers cyclic anchor chains and dangling anchor references (an element anchored to a #id that no longer exists), a page-span heading whose breakBefore is disabled, and an enabled advanced design whose elements never render {titleText}.
debug: {
  warnings: {
    missingFont: true,
    looseLines: true,
    headingHierarchy: true,
    consecutiveHeadings: true,
    listAfterHeading: false,
    designIssues: true,
  },
}

Besides these, the panel always lists the warnings the layout itself raises (VDTDocument.warnings), such as a callout that overflows its column (calloutOverflow), and the configuration values the engine replaced (VDTDocument.configWarnings, or collectConfigWarnings(config); see Configuration warnings below).

#Configuration warnings

These mistakes in the configuration itself are never silent, and no toggle hides them except the one the last item names. The engine does not fail on any of them; it substitutes a value, or leaves the setting out, and says so:

  • Unknown number format — an ordered-list numberFormat, a page.pageNumbering.format or a resource type's counterFormat that is none of the numbering format spellings. It numbers in decimal.
  • Font stack in a font family — a fontFamily (or any …FontFamily) that holds a CSS font stack. The text is set in the stack's first family (see One family per fontFamily).
  • Side column with no room — a 'oneAndHalf' layout's sideColumnPercent (the document's, or a heading style's own layout) that would leave one of the columns under 1% of the content width, or that is not a number. The columns are cut at the nearest value both can take, and used names it (sideColumnPercentClamped; see the 'oneAndHalf' layout).
  • Column count out of range — a 'multiple' layout's columnCount (the document's, or a heading style's own layout) that is not a whole number from 3 to 8. The page is cut into the nearest count that is (3 for a value that is not a number), and used names it (columnCountClamped; see the 'multiple' layout).
  • Character grid too large — a cjk.grid with more characters per line or lines per page than the margins leave room for. The grid is set with the most that fit, and used names the number (cjkGridClamped; see Character grid).
  • Unknown heading setting — a key that headings, headings.balancing, a heading level, a heading style or a paragraph style does not have: a misspelt letterSpacng, a tracking borrowed from another tool, a level on a heading style, a fontStyle: 'italic' on a paragraph style (which takes italic: true). A tab stop is checked the same way (a leaders for leader), and so are a drop cap, lineNumbers, canvasViewer, checks, codeStyle and the comics settings. The engine ignores it (up to postext 1.4 it did so without a word). value is the key, used is empty, and suggestion names the setting it is closest to, when one is a letter or two away or differs only in case (unknownConfigKey).
  • Unknown setting value — a setting that takes one of a few words but holds another, such as direction: 'right' (it takes auto, ltr or rtl). The engine reads the default instead, and used names what that came to: for direction, the direction of the document language (unknownConfigValue). A tab stop's align that is none of its four words is read as 'start', and a position that is no length, 'end' or percentage leaves the stop out (used is 'none'). The words of the comics settings are checked too (Comics › Comic warnings): used is the value the setting resolved to (a balloon style's own default, for a built-in style), and suggestion names the word the value is closest to, when one is close. The level and mode of the contrast check are checked the same way: used is 'AA' or 'auto'. canvasViewer.pageGap and canvasViewer.rowGap are checked the same way: used is the whole number from 0 to 200 the value was read as (since postext 1.43). So are print.standard, print.outputProfile and print.renderingIntent (used is what the default came to), and a maxWords or maxChars of checks.contentInConfig that is not a whole number of 0 or more.
  • Line numbers in vertical text — lineNumbers.enabled: true in a document set vertically (layout.writingMode: 'vertical-rl'). Vertical pages get no line numbers, and used is false (lineNumbersUnsupported; see Line numbers).
  • Text wrap in vertical text — a resource type's defaultPlacement.wrap in a document set vertically. Vertical pages set no text beside a figure, and used is none (wrapUnsupported; see Document format › Text wrap). A wrap that names no side is an unknown setting value.
  • Box style based on another — a callout style whose extends names no style of calloutStyles (calloutStyleExtendsUnknown, with the closest id as suggestion), or whose extends chain comes back to it (calloutStyleExtendsCycle, value the loop a → b → a). The style stands alone, with the built-in values for what it leaves unset (see Styles based on another).
  • Page templates and label styles — a problem in pageTemplates or labelStyles: an id or a name used twice, extends, anchors or chained frames that loop, a style, frame or template that does not exist, a minimum above its maximum, an anchor's label style that labelStyles lacks (checked when the resources are given: collectConfigWarnings(config, { resources })). Their path is a JSON pointer (/pageTemplates/3/frames/2/style); each kind is listed with its cause and fix in Page template warnings.
  • Content in a design — a design text element whose text, beyond its placeholders, is longer than a short label: the book's text kept in the configuration. One warning per setting (a heading style, the header, a part design), with the path of each text (contentInConfig; see Content check). Unlike the others, it can be turned off: checks.contentInConfig.enabled: false.

The Sandbox lists them in the Checks panel with the path of the setting. In code, buildDocument puts them on the document as configWarnings (absent when the configuration is clean), and collectConfigWarnings(config) returns them without laying anything out:

import { buildDocument, collectConfigWarnings } from 'postext';
 
// Plain JavaScript: in TypeScript, 'roman' does not type-check to begin with.
const config = { bodyText: { fontFamily: 'EB Garamond, serif' }, orderedLists: { numberFormat: 'roman' } };
const doc = buildDocument({ markdown }, config);
doc.configWarnings;
// [{ kind: 'fontFamilyStack', path: 'bodyText.fontFamily', value: 'EB Garamond, serif', used: 'EB Garamond' },
//  { kind: 'unknownNumberFormat', path: 'orderedLists.numberFormat', value: 'roman', used: 'arabic' }]
collectConfigWarnings(config); // the same list

Every nested partial configuration is checked too: heading styles, the lists inside parts, htmlViewer.overrides, design elements.

formatWarning (see Warnings in the document) describes them too, with the path of the setting first — bodyText.fontFamily: font stack "EB Garamond, serif" — set in "EB Garamond", headingStyles[0].letterSpacng: unknown setting "letterSpacng" — ignored (did you mean "letterSpacing"?) — so a host can log all three lists a build returns in one loop.