Skip to main content

Chapter 3.18 · Part II · The craft

Programmatic usage: PDF files

postext-pdf from code: installation, the API, font providers in the browser and in Node, CJK fonts, resource bytes, vertical text, workers and print-ready files

Updated 2026-11-1029 minIn chapter 3 Configurationenescadefritptzhjaar

In short

This page is for people who write code and want a PDF file. It shows how to install the PDF package and turn a laid-out book into a file in a few lines. The package needs the font files, so the page explains how to give them to it, in a browser or on a server. It covers fonts for Chinese, Japanese and Korean, pictures, text set from top to bottom and links. It ends with a complete example and with files ready for a printer.

#Generating PDFs

PDF output lives in a separate package, postext-pdf, so that web-only integrations do not pay the cost of pdf-lib and @pdf-lib/fontkit. The PDF backend does not re-measure text: it consumes the exact same VDTDocument you would feed to renderToCanvas or renderToHtml and translates its pixel-space coordinates into PDF points. The three outputs are therefore guaranteed to agree on line breaks, column heights, and resource placement.

In the browser, build the VDT through the Web Worker. renderToPdf itself is fast once the VDT exists — the expensive part is the layout pipeline that produced it. Running that pipeline on the worker keeps the UI responsive and lets a PDF export reuse the same measurement cache the live preview already warmed up. See Driving PDF export from the worker for the recommended flow. The main-thread examples below are the reference for what the arguments mean — for UI code, build the VDT in the worker first and only call renderToPdf directly.

#Installation

npm install postext postext-pdf

postext is a peer dependency of postext-pdf. Each postext-pdf release needs the postext it was released with, or a later one of the same major (its peer range is a caret range on that version: ^1.5.0 for 1.5.0), because it imports helpers postext added in that release. Upgrade the two together, and on a CDN pin them to the same version.

#Public API

The package exposes a single entry point and a handful of types:

  • renderToPdf(doc, options): Promise<Uint8Array> — takes a VDTDocument (or a book's chapters as an array of them) and returns the raw PDF bytes.
  • PdfFontProvider — the callback signature (family, weight, style, request?) => Promise<Uint8Array | Uint8Array[]> that renderToPdf uses to request font bytes when it needs to embed a new family/weight/style combination. request.codePoints holds the characters the pages set in that face; the answer is one file, or several that make the face together (see Chinese, Japanese and Korean fonts).
  • declaredFontFile(bytes, { unicodeRange?, order? }): PdfFontFile — a face file that records how the page declared it: the unicode-range of its @font-face rule and its place in the declaration order. A PdfFontFile is a Uint8Array with those two optional properties (see Chinese, Japanese and Korean fonts). Since postext-pdf 1.30.
  • RenderToPdfOptions — { fontProvider, forms?, resourceBytes?, previewBytes?, outlines?, accessible?, colorSpace?, pageNegative?, characterGrid?, baselineGrid?, onProgress?, onWarning?, rasterizeSvg?, harfbuzzWasm?, print?, outputProfile?, profileBaseUrl?, date? }. forms sets how form fields write numbers (currency, its side, separators) and the face they show values in (font; see Form fields). outlines, accessible and colorSpace fall back to the document's pdfGeneration when left out (see PDF generation (config)). resourceBytes is described in Resource bytes and print masters; onWarning in Which faces the provider is asked for and Warnings in the document. characterGrid: true prints the grid cjk.grid.show draws on screen, which the PDF otherwise leaves out (see Character grid). harfbuzzWasm says where to load HarfBuzz's harfbuzz.wasm from (a URL, relative to the page, or the file's bytes) for a document with right-to-left or joining text; when it is left out, postext-pdf tries the copy beside its own module, then the same harfbuzzjs release from jsDelivr and esm.sh. print takes the print production settings (PDF/X standard, output profile, black, preflight), falling back to the document's print; with a PDF/X standard, or colorSpace: 'cmyk', every colour is separated through the ICC output profile, whose bytes outputProfile gives (otherwise it is fetched from profileBaseUrl, by default the npm CDN copy of postext's icc/ folder). date (a Date, a time in milliseconds or a date string, as createBundle's mtime) is the file's creation and modification date and, in a PDF/X file, the dates of its XMP packet and the source of its document id: the same document rendered twice with one date gives the same bytes. Left out, the file carries the time of the call. An invalid date throws.
  • PdfWarning — a non-fatal problem reported through onWarning; narrow on kind: 'fontFallback' (PdfFontFallbackWarning), a face set in another cut of its family; 'missingGlyph' (PdfMissingGlyphWarning), characters that no file of a face has a glyph for; 'variableFontDefaultInstance' (PdfVariableFontWarning), a variable font asked for at a weight other than its default instance; 'cffEmbeddedWhole' (PdfCffEmbeddedWholeWarning), a CFF face over 2 MB embedded whole; 'complexShapingUnavailable' (PdfComplexShapingWarning), right-to-left or joining text drawn without HarfBuzz, which could not be loaded (reason lists where it was looked for), so Arabic marks are misplaced; 'outputProfileUnavailable' (PdfPrintWarning), a CMYK render whose output profile could not be loaded, converted with the naive formula; 'pageNegativeIgnored' (PdfPrintWarning), the page negative left out of a PDF/X-1a file; 'spotTintsExhausted' (PdfPrintWarning), a render that ran out of codes for distinct spot tints (some 25 million) and printed the rest in process; 'spotInkRenamed' (PdfPrintWarning), an ink whose plate is written under another name (see Spot colours); 'imageProfileUnavailable' (PdfPrintWarning), the profile assigned to RGB pictures that could not be loaded, so their own profiles were used; 'pictureOriginalUnreadable' (PdfPrintWarning), a TIFF or Photoshop original that could not be decoded, printed from its preview (previewBytes) or as a placeholder; 'plateMixesApproximated' and 'artworkOffPlates' (PdfPrintWarning), a job on a few plates (print.plates) that ran out of codes and set the colours past them as the nearest mix it had already coded, or that placed a PDF page or a picture it could not decode with their own inks; or 'missingImage', an image with no bytes drawn as a placeholder (reported only to an onWarning you pass; the font warnings without one go to console.warn).
  • inspectPrintMaster(bytes): Promise<PrintMasterReport> — reads the first page of a PDF print master and reports the fonts it uses without embedding them (nonEmbeddedFonts), whether it paints in RGB (rgb) and whether it uses transparency (transparency), for the preflight.
  • inspectPrintPdf(bytes): Promise<PrintPdfReport> — reads a finished PDF back as a printer's preflight would, every page of it: the version and page count, the PDF/X identification and output intent (and whether its profile is embedded), the trim size and the smallest bleed, pages with another trim size, without a TrimBox or with a page box that is not four numbers (malformedBoxPages, read as missing), the fonts (fonts: name, embedded or not, type; a face used both embedded and not is listed once each way), what it paints in (CMYK, grey, spot inks by name, registration, and RGB split into deviceRgb, with no profile, and iccRgb, with one, each in vector paint or images), transparency, overprint, annotations, an interactive form and whether it is tagged. Besides the pages it reads annotation appearances, the form's fields and default resources, patterns, Type 3 glyphs and inline images. It reads what the file says, not what the configuration asked for, and it does not read picture resolution, total ink, hairlines or trapping. It shares its walk over the pages with inspectPrintMaster, which reports RGB in shadings, patterns and Type 3 glyphs too.
  • decompressWoff2(bytes): Uint8Array — helper that turns a WOFF2 file into TTF bytes, which is the format pdf-lib can embed directly.
  • createPdfWorker(options?), from postext-pdf/worker — the same render on a Web Worker; see Rendering the PDF on a worker.

#Minimal example

import { buildDocument } from 'postext';
import { renderToPdf } from 'postext-pdf';
 
const vdt = buildDocument(
  { markdown: '# Chapter One\n\nThe story begins here…' },
  {
    page: { sizePreset: '17x24' },
    layout: { layoutType: 'double' },
    bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 9, unit: 'pt' } }, // 9 pt overrides the 8 pt default
  },
);
 
const pdfBytes = await renderToPdf(vdt, {
  fontProvider: async (family, weight, style) => {
    // Return TTF bytes for this family/weight/style.
    // See the "Font provider" section below for a real implementation.
    const res = await fetch(`/fonts/${family}-${weight}${style === 'italic' ? 'i' : ''}.ttf`);
    return new Uint8Array(await res.arrayBuffer());
  },
});
 
// `pdfBytes` is a Uint8Array — save, download, or stream it.
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
window.open(url);

#Why a font provider?

pdf-lib embeds real font files into the PDF — the browser's installed fonts are not available at render time, and a font you only loaded for on-screen measurement is not, on its own, enough to produce a self-contained PDF. renderToPdf scans the pages for every face they paint (one per family|weight|style combination — see Which faces the provider is asked for) and calls your provider once per unique combination. The provider returns a Uint8Array of TTF or OTF bytes, or a list of them for a face served as several files (see Chinese, Japanese and Korean fonts); pdf-lib subsets TrueType outlines and embeds CFF (.otf) files whole. A CFF face is declared as one: a CIDFontType0 font with its CFF program in FontFile3 (CIDFontType0C), which pdffonts lists as CID Type 0C and print preflights expect. A CID-keyed CFF face (Source Han, the .otf files of Noto CJK) keeps the TrueType declaration, because its glyph numbering does not match the one the text is written with; use the TrueType builds of those families for print. Faces the provider answers with the same file, such as a regular cut standing in for the bold a family lacks, share one embedded font. A face that no page ends up drawing with, such as the face of an SVG figure's text when the figure is drawn as a picture, is left out of the file.

Use per-weight static fonts, not a single variable font. Google Fonts often serves one variable WOFF2 per family covering the whole weight axis. pdf-lib can only embed the default instance from a variable file, so a bold paragraph would render at regular weight. Fontsource publishes per-weight static WOFF2 files that solve this cleanly — this is the pattern the sandbox uses. A variable file asked for at a weight other than its default instance is reported as a variableFontDefaultInstance warning.

Every word of the text lands where the layout put it. In paragraphs, list items, quotes, boxes and other flowing text, each word starts at the position the VDT measured, so a difference between the browser's widths and the embedded face's never builds up along a line. A line with no inline formatting is painted as one text object that moves the pen between words; justified lines, centred ones and lines with formatting are painted word by word. A character the face has no glyph for (the browser measured it in another font, and the PDF paints it as the face's missing-glyph box) does not move any of the words after it, and is reported once per face as a missingGlyph warning. A space the face lacks, such as a narrow no-break space or a figure space, takes the width the browser gave it, and invisible characters such as the word joiner and the zero-width space are not drawn. If the face lacks the non-breaking hyphen (U+2011), it is drawn with the face's hyphen (U+2010), or with its hyphen-minus when it has no hyphen either, as the browser shows it; Open Sans and Outfit, among others, lack both. Neither case counts as a missing glyph. There are two exceptions. A line with right-to-left letters is still painted as one run (see Languages and scripts). Text placed by a design (running heads and footers, openers, box titles and other design elements) is set with the embedded face's own widths, so a glyph the face lacks there still moves the rest of its line.

#Which faces the provider is asked for

renderToPdf walks the pages the way it paints them and asks the provider only for the faces they draw:

  • the regular face of a block that sets any line, and the bold, italic or bold-italic face of each run actually set that way;
  • chip runs, list markers, and the text of design slots (running heads, folios, opener and part bands);
  • the caption, note and table-cell text of every resource;
  • the faces an SVG figure's <text> names, when the figure is embedded. A family the provider cannot supply at all falls through to the next family in the SVG's font-family list.

So a heading family that is never set in italics is never asked for its italic, and a figure without a note never needs the note faces.

When the provider rejects a face, the render goes on. Another face of the same family is embedded in its place, and a PdfWarning is reported. The substitute is the first face that loads, trying the nine standard weights (100 to 900) in the order CSS font matching uses, which is also the face the browser shows in the preview:

  1. the same style first. For a weight from 400 to 500, the weights up to 500 go first, then the lighter ones from the nearest down, then the heavier ones from 600 up. For a weight below 400, the lighter weights go first, from the nearest down, then the heavier ones. For a weight above 500, the heavier weights go first, then the lighter ones;
  2. then the other style, italic for upright and upright for italic, at the weight asked for and the other weights in the same order.

A family without italics therefore sets its italic runs upright, a family that ships only 400 and 700 takes a 600 as 700, and a family that ships a single cut sets everything in it. The provider is asked one face at a time, in that order, and never twice for the same face, so a face nothing uses is never embedded. A family the provider cannot serve at all is asked for every one of those 18 faces before the render fails.

const bytes = await renderToPdf(doc, {
  fontProvider,
  onWarning: (w) => {
    // { kind: 'fontFallback', family: 'Oswald', weight: 700, style: 'italic',
    //   fallback: { weight: 700, style: 'normal' }, reason: '…', message: '…' }
    console.info(w.message);
  },
});

Without onWarning, the message goes to console.warn. The text keeps its positions, which come from the VDT and were measured with the faces the browser had, so a substitute with different widths can look tight or loose. Supply the real face to fix it. A render still fails (postext-pdf: failed to load font(s): …) only when the provider cannot supply any face of a family at a standard weight, upright or italic.

#Browser font provider (Fontsource + WOFF2)

The sandbox ships createPdfFontProvider() (packages/postext-sandbox/src/viewport/pdf/pdfFontProvider.ts), which you can copy into any browser app. The essentials:

import type { PdfFontProvider } from 'postext-pdf';
import { decompressWoff2 } from 'postext-pdf';
 
const bytesCache = new Map<string, Promise<Uint8Array>>();
 
function fontsourceId(family: string): string {
  return family.toLowerCase().replace(/\s+/g, '-');
}
 
function fontsourceWoff2Url(
  family: string,
  weight: number,
  style: 'normal' | 'italic',
): string {
  const id = fontsourceId(family);
  return `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${id}-latin-${weight}-${style}.woff2`;
}
 
export function createPdfFontProvider(): PdfFontProvider {
  return async (family, weight, style) => {
    const key = `${family}|${weight}|${style}`;
    const cached = bytesCache.get(key);
    if (cached) return cached;
 
    const promise = (async (): Promise<Uint8Array> => {
      const url = fontsourceWoff2Url(family, weight, style);
      const res = await fetch(url, { mode: 'cors' });
      if (!res.ok) throw new Error(`font fetch failed: ${res.status} ${url}`);
      // pdf-lib needs TTF bytes, so decompress the WOFF2 wrapper client-side.
      return decompressWoff2(new Uint8Array(await res.arrayBuffer()));
    })();
 
    bytesCache.set(key, promise);
    return promise;
  };
}

A production version should also:

  • Query the available weights (via https://api.fontsource.org/v1/fonts/{id}) and snap the requested weight to the nearest one the family actually ships, so a request for weight: 600 on a family that only has {400, 700} still succeeds.
  • Fall back from italic to normal when a family has no italic cut for the requested weight, rather than failing the whole render.
  • Reuse the cache across renders (keep the bytesCache module-scoped, not per-call) so regenerating the PDF after a config change is effectively free.

#Chinese, Japanese and Korean fonts

A CJK face does not come as one small file. Fontsource ships Noto Serif SC as about a hundred files per weight, each holding part of the characters and declared in the family's stylesheet with its unicode-range (@fontsource/noto-serif-sc/400.css); the browser downloads the files a page's text touches. The latin file that the provider above fetches holds no Han at all, and the named subsets are incomplete: chinese-simplified of Noto Serif SC lacks 釵, and chinese-traditional of Noto Serif TC has none of the full-width marks (),!?:;.

So a provider may answer a face with several files. renderToPdf passes it the characters the pages set in that face (request.codePoints), collected from every chapter before anything is drawn, and the provider returns the files that hold them, in the order the browser looks them up. Each file is embedded as a subset of its own and each character is drawn from the first file that has a glyph for it: a chapter that touches 60 slices embeds 60 small subsets. When a face is asked for again, say for the text of an SVG figure, the provider is asked only for the characters its files lack. A provider that returns one Uint8Array works as before. The sandbox provider reads the Fontsource stylesheet of the weight and style and fetches the files whose ranges hold the text; the core of it:

import type { PdfFontProvider } from 'postext-pdf';
import { decompressWoff2 } from 'postext-pdf';
 
type Slice = { url: string; ranges: Array<[number, number]> };
 
async function fontsourceSlices(family: string, weight: number, style: 'normal' | 'italic'): Promise<Slice[]> {
  const id = family.toLowerCase().replace(/\s+/g, '-');
  const cssUrl = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/${weight}${style === 'italic' ? '-italic' : ''}.css`;
  const css = await (await fetch(cssUrl)).text();
  return [...css.matchAll(/@font-face\s*{([^}]*)}/g)].map(([, rule]) => ({
    url: new URL(/url\(\.?\/?([^)]+\.woff2)\)/.exec(rule)![1], cssUrl).href,
    ranges: /unicode-range:\s*([^;]+);/.exec(rule)![1].split(',').map((part) => {
      const [lo, hi = lo] = part.trim().slice(2).split('-');
      return [parseInt(lo, 16), parseInt(hi, 16)] as [number, number];
    }),
  }));
}
 
export const sliceFontProvider: PdfFontProvider = async (family, weight, style, request) => {
  // Where ranges overlap, the browser tries the last rule first.
  const slices = (await fontsourceSlices(family, weight, style)).reverse();
  const picked = new Set<Slice>();
  for (const cp of request?.codePoints ?? []) {
    const slice = slices.find((s) => s.ranges.some(([lo, hi]) => cp >= lo && cp <= hi));
    if (slice) picked.add(slice);
  }
  if (picked.size === 0) picked.add(slices[0]!);
  return Promise.all(slices.filter((s) => picked.has(s)).map(async (s) =>
    decompressWoff2(new Uint8Array(await (await fetch(s.url)).arrayBuffer()))));
};

A Latin family goes through the same code: English text gets its latin file alone, Czech gets latin and latin-ext.

A browser does not stop at the first file with a glyph. It sets a character in the file declared last among those whose unicode-range holds it, and the files of a family overlap: Fontsource repeats the ASCII letters of Noto Serif JP in its latin file and in its numbered slices. Two characters set in two files do not kern, so the file decides the width: Chrome 154 sets Shift_JIS 4.25 em wide with the slices declared after latin, and the latin file alone, which kerns t_ and _J, sets it 4.32 em wide. Since postext-pdf 1.30 a provider may say how the page declared each file: declaredFontFile(bytes, { unicodeRange, order }) returns the same bytes carrying the unicode-range of the file's rule, as CSS writes it, and the position of that rule among the face's rules, as any number that grows with the declaration order (the greatest is declared last).

import { declaredFontFile } from 'postext-pdf';
 
declaredFontFile(bytes, { unicodeRange: 'U+0000-00FF,U+0131,U+0152-0153', order: 0 });

In a document shaped in its own language (bodyText.shapingLanguage: 'document', the default), when the files of a face carry their ranges, each character is drawn from the last-declared file whose range holds it and that has a glyph for it, as a browser picks among @font-face rules; a letter and its combining marks stay in one file. A character no range holds is drawn from the first file with a glyph. Plain files, and every file in a document with 'host', are read in the order given, as before, so a provider that describes its files still lists the one declared last first. A face described this way is asked again for every character it was not asked for before, since a file declared later may hold it. The Sandbox's provider describes its files.

Characters that no file of the face has a glyph for are drawn as the font's .notdef glyph (an empty box in most fonts), and renderToPdf reports them once per face after the pages are drawn:

// { kind: 'missingGlyph', family: 'Noto Serif TC', weight: 400, style: 'normal',
//   characters: [',', '!', '?'], message: '…' }

The Sandbox lists these, and the two warnings below, in its Checks panel after each PDF it generates. When the book, its settings or its resources change, they are marked as coming from an earlier PDF until the next one replaces them; opening another book clears them.

  • Bold needs a static file per weight. Fontsource serves each weight of Noto Serif SC and TC as separate static files, so bold works in the Sandbox. The Google Fonts files (NotoSerifSC[wght].ttf, 25 MB) are variable fonts: pdf-lib embeds their default instance, so a 700 face prints at 400, and renderToPdf reports it as variableFontDefaultInstance. For a bundle, cut one static instance per weight with fontTools (fonttools varLib.instancer NotoSerifSC[wght].ttf wght=700) and subset it to the book's characters with pyftsubset.
  • Use TrueType builds. Source Han Serif and the Noto Serif CJK .otf files have CFF outlines, which postext-pdf embeds whole, 8 to 25 MB per weight; a CFF face over 2 MB is reported as cffEmbeddedWhole. The TrueType builds (Google Fonts, Fontsource) are subset to the glyphs used. For Japanese, Noto Serif JP and Noto Sans JP (Google Fonts, or Fontsource's numbered slices), Shippori Mincho, Zen Old Mincho and BIZ UDMincho come as TrueType; Source Han Serif JP and the JP .otf files of Noto Serif CJK are CFF.
  • Japanese forms of a pan-CJK face. The same code point, whether a Han character, a punctuation mark or a quote, can be drawn one way in Japan and another in China, and a pan-CJK face (Source Han, Noto CJK) holds both. The PDF shapes a Japanese document (locale: 'ja'), and an isolate in Japanese (:ltr[…]{lang=ja}) in any document, with the OpenType language system JAN , so the face's locl feature prints the Japanese forms that the canvas and the HTML print through lang. An isolate in another language inside a Japanese book is shaped with that language's forms (the font's default ones for Chinese with 'host') and tagged as a Span with its /Lang. With bodyText.shapingLanguage: 'document', the default since postext 1.30, every document and every isolate is shaped in its own language (ZHS for Simplified Chinese), as the layout measured it; with 'host', Chinese and other documents are shaped with the font's default forms, as before. A face made for Japanese such as Noto Serif JP has Japanese default forms; it still sets the “ ” of Japanese text in their JAN forms.

A character missing from one family is not taken from another: Noto Serif TC does not borrow from Noto Serif SC. Settle coverage when you build the font files; the 红楼梦 showcase copies the glyphs its TC subsets lack from the SC face.

#Server-side font provider (Node, local files)

In Node you can skip the WOFF2 step entirely and read TTF/OTF files from disk:

import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { PdfFontProvider } from 'postext-pdf';
 
const FONT_DIR = '/path/to/fonts';
 
function filename(family: string, weight: number, style: 'normal' | 'italic'): string {
  const slug = family.replace(/\s+/g, '');
  const styleSuffix = style === 'italic' ? 'Italic' : '';
  const weightName =
    weight >= 700 ? 'Bold'
    : weight >= 600 ? 'SemiBold'
    : weight >= 500 ? 'Medium'
    : weight >= 300 ? 'Light'
    : 'Regular';
  return `${slug}-${weightName}${styleSuffix}.ttf`;
}
 
export const localFontProvider: PdfFontProvider = async (family, weight, style) => {
  const buf = await readFile(join(FONT_DIR, filename(family, weight, style)));
  return new Uint8Array(buf);
};

#Resource bytes and print masters

resourceBytes(fileId) returns the raw bytes of a picture, and the backend sniffs them:

  • PNG, JPEG, GIF and WebP embed as images;
  • SVG markup is drawn as vector paths, its text set as real text in the document's embedded fonts, or rasterised at 600 dpi in the browser when it uses features outside the vector subset. A <style> that holds only @font-face rules (faces an author embedded) is skipped and keeps the figure vector (since postext-pdf 1.25); any other style sheet makes it a raster, drawn with the faces its text names inlined from fontProvider (unless diagramStyle.inlineFonts or the resource's svg.inlineFonts is false);
  • TIFF and Photoshop documents (PSD, PSB) print from their own pixels: grey, RGB or CMYK, 8 or 16 bits, with the ICC profile and the resolution they carry. A CMYK one keeps its inks as they are; grey and RGB follow print.imageColor. A Photoshop document is read from the composite image it saves with "Maximize compatibility"; JPEG-compressed TIFF is not read;
  • a PDF has its first page embedded verbatim, as a form XObject.

Each picture is stored in the file once, however many times it is drawn. An SVG drawn as vector paths becomes a form XObject that every page paints, so a frame or a logo in the page design of a thirty-page document is written once, not thirty times; each further page adds a few hundred bytes. Up to postext-pdf 1.4 every page carried its own copy of the paths.

An SVG figure can name a print master in svg.pdfFileId: a single-page PDF of the same figure, typically the original the SVG was exported from. renderToPdf asks resourceBytes for the master's id first. It embeds that page in place of the SVG, with its fonts, gradients and colour spaces intact, wherever the SVG is drawn: as a figure, as the picture of a table cell (TableCell.image), as a design image or as a box icon (its marker too). The VDT carries the master's id on each of those uses (svg.pdfFileId on the figure's resource, pdfFileId on a cell image and on a design image block), so in a book every chapter gets the master. The canvas and HTML backends keep drawing the SVG. The SVG's own bytes are used instead in three cases: the master is missing, it is not a PDF, or single ink is on (diagramStyle.singleInk recolours SVG markup only).

const resources: Resource[] = [{
  id: 'map', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
  svg: { fileId: 'map.svg', width: 800, height: 600, pdfFileId: 'map.pdf' },
}];
const files = new Map([['map.svg', svgBytes], ['map.pdf', masterPdfBytes]]);
const pdf = await renderToPdf(buildDocument({ markdown, resources }, config), {
  fontProvider,
  resourceBytes: (fileId) => files.get(fileId),
});

A host may also return the master's bytes for the SVG's own id, as bundleResourceBytes does; both ways work.

A browser cannot show a TIFF or a Photoshop document, so a bitmap resource made from one keeps two files: bitmap.fileId is a PNG preview, which the canvas, the HTML and the EPUB show, and bitmap.printFileId (with printFormat: 'tiff' | 'psd') is the original. A host returns the original's bytes for bitmap.fileId, as bundleResourceBytes and the Sandbox do, and the PDF prints from it. It passes the preview too, as previewBytes (bundlePreviewBytes for a bundle): an original that cannot be decoded prints from its preview, with a pictureOriginalUnreadable warning, and without one it is a placeholder. decodePrintRaster(bytes) and rasterToRgba(raster) in postext read the original and make the preview; the Sandbox makes it when the file is imported, and a bundle stores the original as resources/<name>.tif or .psd beside the preview.

An Adobe Illustrator file saved with "Create PDF Compatible File" is a PDF, and it can be a print master like any other (.ai). Its swatches are its own plates: the preflight lists those the ink table renames, those no colour of the book defines and, in a job on its own plates (print.plates), those the job does not print, since a placed file is printed as it is.

#Vertical text in the PDF

A vertical page (layout.writingMode: 'vertical-rl') is drawn through a quarter-turn frame, as the canvas paints it, and its text is set down the column:

  • Upright characters are shown through a second Type0 font of the same embedded file: the same CIDFont, widths and ToUnicode map, with Encoding /Identity-V (vertical mode). One run of characters is one text object whose glyphs advance one em down the column by themselves (DW2 [880 −1000]), so readers select and extract a column as one line. The glyphs are shaped with OpenType vert and fwid, which gives brackets, quotes, mainland pause marks, ellipses and dashes their vertical forms; a character that stands upright as it is keeps its horizontal glyph. Nothing of the font is embedded twice.
  • Latin words and long numbers run sideways with the horizontal font; a number in one cell stands upright, squeezed across to one em when it is wider; a mark the font has no vertical form for is turned or moved, as on the canvas.
  • Tracking between characters is written as TJ numbers, which in vertical mode move the pen down the column.
  • Every vertical line is marked with an /ActualText of its text, so copying and text extraction read it as written. pdftotext and pdf.js read the columns top to bottom, right to left; pdf.js starts a new line at a number set in one cell.
  • Links, bookmarks and destinations are mapped onto the sheet: a link over a vertical line is a tall, thin rectangle, and a bookmark opens the page at the top of its heading's column.
  • A tagged PDF declares the writing mode on its Document element (the Layout attribute WritingMode /TbRl, which every element inherits); PDF/UA-1 validation (veraPDF) passes on a vertical chapter.
  • Viewers: Acrobat, Preview, Chrome (PDFium), pdf.js and Poppler render the vertical fonts. A right-bound book (page.binding) also asks viewers to lay its spreads out right to left (/Direction /R2L, /PageLayout /TwoPageRight); Acrobat and Foxit follow it, Chrome does not.

A 43-page chapter set in Noto Serif TC (the book's characters, TrueType) is about 820 KB, most of it the two font subsets.

#Form fields

A chip with a field attribute is a fillable form field (AcroForm). The chip lays out and paints its box as any chip does: its style gives the look and the least width (minWidth), its words are the field's default value. The PDF puts an interactive field on the box; a name used twice is one field with two widgets.

Quantity :chip[ ]{style="field" field="pos.a.qty" kind="number"}
Price :chip[120]{style="field" field="pos.a.price" format="currency"}
Total :chip[ ]{style="field" field="pos.a.total" format="currency" calc="product(pos.a.qty, pos.a.price)"}
Service :chip[ ]{style="box" field="pkg.a" kind="checkbox" on="1"}
Order total :chip[ ]{style="field" field="order.total" format="currency" calc="sum(pos.a.total, product(pkg.a, 161.75))"}
Size :chip[M]{style="field" field="size" kind="choice" options="S|M|L"}
  • kind: text (default), number, checkbox, choice (with options, separated by |). A chip with format or calc and no kind is a number field.
  • on (a check box): the name of the box's on state, which is the value its scripts read when it is ticked. on="1" makes a ticked box count 1 in a calculation, so product(pkg.a, 161.75) adds a fixed price when the box is ticked. The default is Yes, which a calculation counts as 0.
  • format: currency, decimal (two decimals), integer. Written as Acrobat's AFNumber_Format and AFNumber_Keystroke, in the document language's separators (1.234,56 in German) unless RenderToPdfOptions.forms.separatorStyle says otherwise; the currency is forms.currency (default €), before the number unless forms.currencyBefore is false. A default value is drawn formatted.
  • calc: sum(…), product(…), min(…), max(…) or avg(…). The arguments are other fields by name, numbers (with a point as the decimal mark, 161.75) and nested calculations: sum(pos.a.total, pos.b.total, product(pkg.a, 161.75)). A calculation over fields alone is written as AFSimple_Calculate. One with numbers or nested calculations is a short Calculate script of its own, which reads each field the same way (AFMakeNumber of its value; anything that is no number counts 0) and rounds the result to six decimals. A calculated field is read-only, and the calculation order follows every field it reads, nested ones too. These are formField warnings: a calculation that reads an unknown field (it counts 0), a cycle, a name used for two kinds, and a check box in a calculation whose on value is no number (it always counts 0).
  • readonly, required, multiline, tooltip as their names say.

A field shows its value, and what someone types in, in the face of its chip (forms.font: 'chip', the default), or in a face of the document's fonts that forms.font names ({ family, weight?, style? }, asked of the fontProvider like any other). That face is embedded whole, not as a subset, since a subset has no glyphs for characters typed later; it is embedded once however many fields use it, named in the form's default resources (/DR) and in each field's default appearance (/DA), and the default values are drawn with it. A whole face adds its full file to the PDF (a Latin text face is typically 50–300 KB, a CJK face several MB), on top of the subset the page text uses. The provider may answer TrueType, OpenType or WOFF2 (decompressed before embedding). The fields fall back to Helvetica, with a formField warning, when the face cannot be embedded whole: its licence forbids embedding (OS/2 fsType restricted or bitmap only), the provider gives it in several files (a sliced face), or its format is WOFF or a collection. forms.font: 'helvetica' uses Helvetica without embedding anything. Some viewers (macOS Preview, for one) draw the text being typed in a face of their own; the value is the same.

Acrobat, Foxit, pdf.js (Firefox) and most viewers run these scripts. A print standard (PDF/X) allows no interactive fields: there the values are painted as text, a number field's value as the form shows it (formatted, set to the box's end inside the style's own paddingX, in the chip's colour).

The canvas paints a number field the same way, so the preview matches the PDF: pass renderPageToCanvas (or renderPage, renderToCanvas) the same forms option as renderToPdf; the separators default from the document's locale (else its hyphenation language) in both. One rule writes the numbers everywhere, and postext exports it for other writers: formNumberStyle(forms, lang) resolves the options, formatFieldNumber(value, format, style) formats a value (undefined for text that is no number), and numberFieldText(field, words, style) gives what a painted number field shows. The display list carries the field on a chip run (inline.field, with the layout's sizePx and padPx).

A book can keep these options in its configuration: pdfGeneration.forms takes the same fields (currency, currencyBefore, separatorStyle, font). renderToPdf and the canvas take each one from their own forms option first, then from the first document's pdfGeneration.forms, then from the defaults. It changes no layout, only how the fields are written and painted. In the Sandbox it is the Form fields group of the PDF section.

pdfGeneration: {
  forms: { currency: 'USD', currencyBefore: true, separatorStyle: 0, font: { family: 'Lora', weight: 400 } },
}

From esm.sh in a browser, import https://esm.sh/postext-pdf?bundle. esm.sh's default build of pdf-lib puts its annotation classes in a module of their own, and pdf-lib then refuses every field's widget: the PDF keeps the boxes but loses the formats, calculations and flags, with a formField warning for each field. ?bundle builds pdf-lib as one module and leaves postext outside it, shared with the page. A bundler (Vite, webpack, Next.js) and Node are not affected.

The IDML export writes the same fields as InDesign form fields (see Programmatic usage › InDesign packages).

The words of a Markdown link (see Document format › Links) become URI link annotations, one per run of linked words on a line. Each covers the line box and has no border. In an accessible render, each run is a Link element whose /Contents is its text. Only absolute http:, https:, mailto:, tel: and ftp: targets are linked, because a relative URL has no base inside a PDF. Characters outside printable ASCII are percent-encoded. :ref citations and contents rows keep their links inside the document.

#Complete browser example: build, render, download

Putting everything together — build the VDT, render to PDF, and trigger a download from the browser:

import { buildDocument, createMeasurementCache } from 'postext';
import { renderToPdf } from 'postext-pdf';
import { createPdfFontProvider } from './pdfFontProvider';
 
const fontProvider = createPdfFontProvider();
 
export async function downloadPdf(markdown: string, config: PostextConfig) {
  const cache = createMeasurementCache();
  const vdt = buildDocument({ markdown }, config, cache);
 
  const bytes = await renderToPdf(vdt, { fontProvider });
 
  const blob = new Blob([bytes.slice().buffer], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'document.pdf';
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

Important: call ensureConfigFontsLoaded(config) (or equivalent) before buildDocument when your config references web fonts. Layout is measured against whatever font metrics the browser currently has for that family — if the real font has not landed yet, the VDT is measured against a fallback and the PDF will not match the canvas or HTML output. The sandbox does this explicitly before every render (see packages/postext-sandbox/src/viewport/pdf/PdfViewport.tsx).

#Live example: a PDF in the browser

The complete flow above, running in the browser: the pen imports postext and postext-pdf from a CDN, loads the web fonts, builds the document, embeds the Fontsource cuts through the font provider and hands the bytes to a link that opens the file in a new tab, and to a download link. The PDF you get has the same line breaks as the canvas and HTML output, real embedded fonts, and outline bookmarks.

Postext · generate a PDF in the browser
import { buildDocument } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
 
const markdown = `# The Lantern
 
The lantern hung from a nail by the door, and every evening someone lit it. Nobody remembered who had put the nail there, or why the lantern was never moved.
 
## Two columns
 
Postext lays this text out in **two columns**, breaking each paragraph with the *Knuth–Plass* algorithm and hyphenating with TeX patterns. Widows and orphans are avoided, and the columns are balanced on the last page.
 
The light it gave was small, but it was enough to find the step. The lantern hung from a nail by the door, and every evening someone lit it. Nobody remembered who had put the nail there, or why the lantern was never moved.`;
 
const config = {
  page: { sizePreset: '17x24' },
  layout: { layoutType: 'double' },
  bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 10, unit: 'pt' } },
};
 
// The PDF embeds real font files. Fontsource publishes one static WOFF2 per
// weight and style; decompress it to the TTF bytes pdf-lib can embed.
const fontProvider = async (family, weight, style) => {
  const id = family.toLowerCase().replace(/\s+/g, '-');
  const url = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@latest/files/${id}-latin-${weight}-${style}.woff2`;
  const res = await fetch(url);
  if (!res.ok) throw new Error(`font fetch failed: ${res.status} ${url}`);
  return decompressWoff2(new Uint8Array(await res.arrayBuffer()));
};
 
// Layout is measured with the browser's fonts, so load them before building:
// otherwise the PDF would not match the canvas or HTML output.
await Promise.all([
  document.fonts.load('16px "EB Garamond"'),
  document.fonts.load('bold 16px "EB Garamond"'),
  document.fonts.load('italic 16px "EB Garamond"'),
  document.fonts.load('bold 16px "Open Sans"'), // the default heading face
]);
 
const doc = buildDocument({ markdown }, config);
 
// Same VDT, now translated to PDF points: identical line breaks and placement.
const bytes = await renderToPdf(doc, { fontProvider });
 
// A PDF viewer cannot run inside this sandboxed result frame,
// so hand the file to a new tab and to a download link.
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
document.getElementById('open').href = url;
document.getElementById('download').href = url;
document.getElementById('links').hidden = false;
document.getElementById('status').textContent =
  `${doc.pages.length} page(s) · ${(bytes.length / 1024).toFixed(0)} KB PDF`;
index.html
<p id="status">Rendering…</p>
<p id="links" hidden>
  <a id="open" target="_blank" rel="noopener">Open lantern.pdf in a new tab</a> ·
  <a id="download" download="lantern.pdf">Download it</a>
</p>
style.css
body {
  margin: 16px;
  font-family: system-ui, sans-serif;
}

Loads an interactive editor from codepen.io. The example imports the latest postext release from a CDN.

#Rendering the PDF on a worker

postext-pdf/worker moves renderToPdf off the main thread. The worker writes the text, the vector figures, the structure tree and the file itself. Two jobs need the page, so the worker asks the main thread for them: fetching fonts, and rasterising an SVG through an <img>. For a book of hundreds of pages, rendering takes seconds that would otherwise freeze the page; for a few pages, calling renderToPdf directly is simpler.

import { createPdfWorker } from 'postext-pdf/worker';
 
const pdfWorker = createPdfWorker();
const bytes = await pdfWorker.render(docs, {
  fontProvider,                                     // runs on this thread
  resourceBytes: new Map([['map.svg', svgBytes]]),  // a Map; its buffers move to the worker
  onProgress: ({ phase, pages, totalPages }) => showProgress(phase, pages, totalPages),
  onWarning: (w) => console.info(w.message),
});
pdfWorker.dispose();
  • render(docs, options) takes one document or a book's array of chapter documents. It takes the options of renderToPdf, with two differences. resourceBytes (and previewBytes) is a Map<string, Uint8Array> whose buffers are transferred, so pass copies of bytes you keep. rasterizeSvg, when given, runs on the main thread; by default the page's own Image and canvas do the job.
  • One handle renders one document at a time. dispose() terminates the worker and rejects any render still pending with an AbortError (DOMException): treat it as a cancellation. A font or picture your provider answers after dispose() is dropped.
  • inspect(bytes) reads a finished PDF back on the worker (inspectPrintPdf) and resolves with its report, or undefined when the bytes cannot be read as a PDF. The bytes are copied, so yours stay usable. Nothing is read unless you call it.
  • createPdfWorker({ worker }) takes a Worker you create, for build tools that control worker URLs. That worker must run postext-pdf/worker/entry.

From a CDN. By default the worker script is loaded from the package's own URL (new URL('./pdf.worker.js', import.meta.url)). A page on another origin may not start it: imported from esm.sh, createPdfWorker() throws Failed to construct 'Worker': Script at 'https://esm.sh/postext-pdf@…/pdf.worker.js' cannot be accessed from origin …. Start a same-origin module worker that imports the entry instead (when you pin a version, pin the same one in both URLs):

import { createPdfWorker } from 'https://esm.sh/postext-pdf/worker';
 
const entry = URL.createObjectURL(new Blob(
  ["import 'https://esm.sh/postext-pdf/worker/entry';"],
  { type: 'text/javascript' },
));
const pdfWorker = createPdfWorker({ worker: new Worker(entry, { type: 'module' }) });

The layout worker from postext/worker does not need it: createLayoutWorker() starts its own entry from esm.sh with no options, and from any other server with its url option (see Loading the worker from a CDN).

For production print workflows, tune these configuration options before rendering:

  • page.cutLines.enabled: true — adds bleed area and crop marks around the trim, and gives every page a TrimBox and a BleedBox. See Cut lines.
  • print: { standard: 'pdfx4', outputProfile: 'fogra51' } (or 'pdfx1a') — a PDF/X file with the output intent, the identification and the boxes a printer checks; every colour and RGB picture separated through the ICC profile, 100 % K overprinting and large black areas in rich black. See Print production (config).
  • colorSpace: 'cmyk' (or pdfGeneration: { forceColorSpace: true, colorSpace: 'cmyk' }) — the same separation without the PDF/X identification (crop marks are always in registration colour). PDF print masters are embedded as they are.
  • page.dpi: 300 — the layout's px per inch: a bitmap with no resolution of its own prints at this resolution at its natural size. The preflight reports pictures under 300 ppi at their printed size.
  • ColorValue.cmyk — a colour authored in CMYK prints with its exact values.
  • { pageNegative: true } in RenderToPdfOptions — inverts the trim area using a Difference blend mode (cut marks stay un-inverted). Useful for preflight checks on dark-on-light typography.

#Spot colours

A spot colour (a Pantone, a corporate ink, a varnish) prints on its own plate. A colour with model: 'spot' carries its ink in ColorValue.spot: name is the plate's name as the printer knows it, cmyk is what the ink looks like at 100 % (the alternate the PDF gives anyone without the ink), tint is the strength in percent (100 by default), and overprint makes the ink overprint what is under it instead of knocking it out, like a varnish. hex is its screen rendering.

A CMYK or PDF/X PDF writes each ink as a Separation colour space named after it, and paints every colour of that ink at its tint: colours with the same name share a plate. That covers the usual jobs: two colours (black and a spot), process with a few elements in a spot ink, and a varnish overprinted on chosen areas. When diagramStyle.singleInk uses a spot ink, SVG diagrams print in tints of that plate. An RGB PDF and the screen paint the colour's hex.

Spot inks inside an SVG. See How single ink works.

colorPalette: [
  { id: 'brand', name: 'Brand', value: { hex: '#1f3f99', model: 'spot', spot: { name: 'PANTONE 286 C', cmyk: { c: 100, m: 66, y: 0, k: 2 } } } },
  { id: 'brand-40', name: 'Brand 40 %', value: { hex: '#a5b6dd', model: 'spot', spot: { name: 'PANTONE 286 C', cmyk: { c: 100, m: 66, y: 0, k: 2 }, tint: 40 } } },
  { id: 'varnish', name: 'Varnish', value: { hex: '#f4f4ee', model: 'spot', spot: { name: 'Varnish', cmyk: { c: 0, m: 0, y: 10, k: 0 }, overprint: true } } },
],
diagramStyle: { singleInk: true, inkColor: { hex: '#1f3f99', model: 'spot', paletteId: 'brand' } },

The preflight counts a spot colour as one ink, keeps it off the coverage limit and lists the job's spot inks (spotInks), the inks the SVG pictures name included. It warns when one ink is defined twice with different values (spotInkConflict; the PDF uses the first), when an SVG names an ink that no palette colour, nor an ink-table entry with cmyk, defines (spotInkUndefined; it prints on a plate of its own, with the SVG colour's CMYK as alternate, one plate per name), when the PDF has to write a plate name differently (spotInkName, see below), and when two plate names differ only in case or spacing (spotInkSimilar: PANTONE 185 C and Pantone 185 C would be two plates). preflightDocument learns which inks an SVG names from svgInks(fileId), a function that returns the names svgSpotInks(markup) finds in the file; the Sandbox's Checks panel and postext check pass it.

Plate names. The name is written as typed: accents, symbols and # reach the PDF in UTF-8 (Rojo Médica is /Rojo#20M#C3#A9dica), which is how Acrobat, a RIP and the printer's preflight read it. A name a plate cannot carry is written under another: All, None, Cyan, Magenta, Yellow and Black, in any case, get the word ink after them (All ink); control characters are dropped; and a name over 127 UTF-8 bytes is cut at a character boundary and ends in a short hash, so two long names that begin alike stay two plates. The preflight's spotInkName says why (problem: reserved, process, control or tooLong) and which name the PDF writes (written), and the render reports each rename through onWarning (spotInkRenamed). To choose the name yourself, give the ink a pdfName in the ink table.

One ink per colour. A print render knows a colour by its screen hex, so two colours that state their print values — two inks, or an ink and a colour authored in CMYK — must not share one. When they do, the later one moves to the nearest free hex, a step away and invisible on screen, and each prints on its own plate. A plain screen colour (model: 'hex') with the hex of a spot colour prints as that spot colour; link it to the palette entry to make it explicit. The colour that moves changes on screen too, by one step (1/255) in one channel, blue first, on every output (canvas, HTML, EPUB and an RGB PDF). That is far below what the eye tells apart, and it is the price of a print render that reads inks from the painted hex. The stored configuration does not change.

The ink table

print.inks says how the job's inks reach the printer, whatever the colours, the SVGs and the imported files call them. An ink it does not list prints as its colours define it.

interface PrintInk {
  name: string;                    // The ink as a colour's spot.name or an SVG names it.
  aliases?: string[];              // Other names of the same ink: they print on this plate.
  pdfName?: string;                // The plate's name in the PDF. Defaults to name.
  output?: 'spot' | 'process';     // 'process' prints the ink in CMYK, from its alternate.
  cmyk?: CmykPercent;              // The alternate at 100 %, over the colours' own.
  overprint?: boolean;             // Over the colours' own.
}

Names and aliases are matched ignoring case and runs of spaces. Renaming takes one line however many colours use the ink; an alias merges the names a designer's swatch, an SVG (data-spot, icc-named-color) or an older palette gave the same ink onto one plate; and output: 'process' prints an ink in CMYK when the press has no unit for it, every tint included.

In the Sandbox the table is Design › Export › Print preparation › Ink table: a card per ink with its Ink name, Aliases, Plate name in the PDF, Prints as, Alternate CMYK and Overprint. Inks the colours use lists the inks of the book's colours that the table lacks, each with a button that adds it.

print: {
  standard: 'pdfx4',
  inks: [
    { name: 'Azul corporativo', pdfName: 'PANTONE 286 C', aliases: ['Pantone 286C', 'Azul'] },
    { name: 'Varnish', output: 'process' },
  ],
},

Two-ink printing

print.plates names the plates the job prints on, and nothing else is printed: a book in black and one spot ink, in two spot inks, or in black alone. The process plates are Cyan, Magenta, Yellow and Black; a spot plate is named as the PDF names it, or by a name or alias of the ink table.

interface PrintPlatesConfig {
  inks?: string[];                                // The plates. Empty: every plate, as usual.
  images?: string[];                              // The plates pictures print on: one or two.
  curves?: Record<string, Array<[number, number]>>; // A picture plate's curve: [tone, ink] in percent.
}
  • A colour of an ink the job prints, or a CMYK colour whose channels it prints, is set as it is.
  • Any other colour is projected: it prints as the mix of one plate or two whose appearance through the output profile comes closest to it. A mix of two inks is a DeviceN colour space in the PDF, and a grey stays on Black alone. Rich black is dropped unless the job prints all four process inks.
  • Pictures print as a monotone on one plate, or a duotone on two: the tone of each pixel (its lightness) runs through each plate's curve. images defaults to Black, or to the first plate when the job does not print black. A monotone's curve is a straight line; a duotone puts its first plate on the shadows and its second on the middle tones. curves replaces either.
print: {
  standard: 'pdfx4',
  plates: {
    inks: ['Black', 'PANTONE 286 C'],
    images: ['Black', 'PANTONE 286 C'],
    curves: { 'PANTONE 286 C': [[0, 0], [50, 35], [100, 70]] },
  },
},

The preflight lists the job's plates and each colour the projection moves. A spot ink or a CMYK colour the job does not print is information when its mix lands within ΔE 6 of it, and a warning past that or while the output profile is not loaded (offPlateInk, offPlateCmyk); a screen colour that lands past ΔE 6 is a warning too (offPlateColor). A spot plate that no colour and no ink table entry defines is a warning: it prints and proofs as black. A figure's print master is set aside in such a job and its SVG is set on the plates; a placed PDF page, or a picture that cannot be decoded, keeps its own inks and the render warns (artworkOffPlates). In the Sandbox the plates are set in Print preparation → Plates. Its previews and print preview show the colours as the book defines them, not as the plates print them: look at the PDF, where Check for print lists the inks it uses.

#Pictures' colours

A picture is separated from the colours it was made in. print.imageColor says how its pixels are read:

interface PrintImageColorConfig {
  embeddedProfile?: 'use' | 'ignore';                  // A picture's own ICC profile. Default 'ignore'.
  assignedRgbProfile?: { name: string; fileId: string }; // Read every RGB picture through this .icc instead.
  grayDotGain?: 'profile' | 'none' | number;           // Greyscale pictures on black. Default 'none'.
  cmykProfile?: 'convert' | 'keep';                    // A CMYK picture of another press. Default 'keep'.
}

The defaults keep pictures as earlier versions printed them: every RGB picture read as sRGB ('ignore'), greyscale separated like any other picture ('none') and a CMYK picture's values kept ('keep'). Each behaviour below is the one its field opts into.

  • Its own profile. A PNG (iCCP) or JPEG (ICC_PROFILE) that embeds a profile is read through it, so an Adobe RGB or Display P3 photograph separates as it looks instead of as if it were sRGB. An untagged picture, or one tagged sRGB, is read as sRGB, as before. 'ignore' reads every picture as sRGB.
  • An assigned profile. assignedRgbProfile names a stored .icc every RGB picture is read through, whatever it embeds: for a batch of photographs that lost their profile, say. Its bytes come from resourceBytes; when they are missing, the pictures' own profiles are used, with an imageProfileUnavailable warning.
  • Kept for the RIP. In PDF/X-4 with convertImages: false, a picture with a profile other than sRGB is written in its own colours, tagged ICCBased with that profile, and the printer's RIP converts it.
  • Greyscale. A greyscale picture (a grey PNG or JPEG, or one with a grey profile) prints on black alone, never as a four-colour grey. Its tones, read through its own profile (else as the screen shows them), are matched to the press: 'profile' through the output profile's black, whose dot gain the condition already includes; a number is the press's dot gain at the 50 % tone, in percent (10–30 typically), which is compensated instead; 'none' writes the values as they are, as before.
print: {
  standard: 'pdfx4',
  imageColor: { grayDotGain: 20 },
},
  • A CMYK picture of another press. A CMYK picture whose own profile is another printing condition (a photograph separated for SWOP or for newsprint in a book for FOGRA) is separated again for the output's (cmykProfile: 'convert'), black alone kept black alone: a TIFF or Photoshop picture from its pixels; a CMYK JPEG, whose pixels are not decoded, is tagged ICCBased with its own profile in PDF/X-4 for the RIP to convert, and passed through in PDF/X-1a, which allows no such tag; the preflight warns of it there (cmykImageForeign) when the host gives it the picture's profile (imageProfile). In PDF/X-4 with convertImages: false a TIFF or Photoshop picture is tagged the same way. 'keep' prints every CMYK picture's values as they are.

One picture's own settings. A resource's printColor takes the same fields over the book's print.imageColor, for that picture alone: one photograph whose profile must be ignored, one read through an assigned profile, one grey picture with another dot gain. In the Sandbox, a picture's card sets whether it is read through its own profile ("Colour in print"), how its greys meet the press ("Greys in print") and a profile assigned to it ("Assigned profile", an .icc file); a bundle carries assigned profiles, the book's and a picture's, in its profiles/ folder. The book's own settings are in Print preparation → Pictures.

{ id: 'archive-photo', kind: 'bitmap', bitmap: { fileId: 'photo.jpg', format: 'jpeg', width: 2400, height: 1600 },
  printColor: { embeddedProfile: 'ignore' } }

#Colours authored in CMYK

A colour written in CMYK keeps its exact values: ColorValue.cmyk (percent) is set as it is in a print render, and hex is its screen rendering. A palette entry authored in CMYK covers every colour linked to it.

colorPalette: [
  { id: 'brand', name: 'Brand', value: { hex: '#00a0e3', model: 'cmyk', cmyk: { c: 100, m: 0, y: 0, k: 0 } } },
],

#Colours that overprint

Any colour can overprint in a print render: overprint: true on a ColorValue sets everything painted in it (text, rules, boxes, grounds) over what is under it instead of knocking it out. A process colour is written as it separates, under an overprinting graphics state; a spot colour overprints on its ink's plate, even where the same ink in another colour knocks out. A 100 % K black that overprints keeps the black handling: large areas still get rich black (black.richBlack). An RGB PDF and the screen ignore it. Set it on the palette entry to make every colour linked to it overprint, its tints included; a linked colour takes the entry's setting, not one of its own. A part's or a section's palette keeps it: text in the part's colour overprints too.

colorPalette: [
  { id: 'title', name: 'Title', value: { hex: '#c00020', model: 'cmyk', cmyk: { c: 0, m: 100, y: 80, k: 10 }, overprint: true } },
],

A print render knows a colour by the hex the layout paints, so a colour that overprints never shares its hex with one that knocks out. When they coincide, the one that overprints moves one step (1/255 in one channel), as spot colours do; a part's colour for an entry that overprints moves the same way off any colour of the book that knocks out. A colour that overprints and puts no ink down (paper white, an ink at 0 %) disappears on press: the preflight reports it as critical (overprintWhite). A render with more distinct colours than it has codes for (some 25 million) knocks the rest out and warns (overprintsExhausted). In the Sandbox, the colour picker's Overprint in print switch sets it.

#Preflight

interface PrintPreflightConfig {
  enabled?: boolean;
  minImageResolution?: number;       // ppi at the printed size.
  criticalImageResolution?: number;
  minRuleWidth?: Dimension;
  smallTextSize?: Dimension;
  safeZone?: Dimension;
  bleedSnap?: Dimension;
  checkFonts?: boolean;
}
PropertyTypeDefaultDescription
enabledbooleantrueRun the checks.
minImageResolutionnumber300A placed bitmap under this many pixels per inch at its printed size, crop included, gets a warning: figures, table-cell pictures, design images, comic panels. A bitmap with no resolution of its own prints at page.dpi at its natural size, so a page laid out at 150 dpi prints every such picture at 150 ppi; one with a resolution (bitmap.resolution, layout.bitmapResolution) prints at that resolution at its natural size.
criticalImageResolutionnumber150Under this the warning is critical. Never above minImageResolution.
minRuleWidthDimension0.25ptRules, borders, column rules, table rules and comic panel borders thinner than this.
smallTextSizeDimension9ptText under this size set in more than one ink (a process colour, rich black): it blurs when the plates shift. Black text, K only, never counts.
safeZoneDimension5mmText closer than this to the trim, where the guillotine may cut it.
bleedSnapDimension3mmA box or picture that stops this close to the trim without reaching the bleed: run it into the bleed or pull it in.
checkFontsbooleantrueReport fonts a placed PDF does not embed (the Sandbox inspects each print master with inspectPrintMaster). Postext embeds every font it sets.

preflightDocument(doc, options) runs the checks on a laid-out document and returns a list of issues, each with a kind, a severity ('critical', 'warning' or 'info'), the book-absolute pageIndex, the offending rect (page px) and, when the element has one, its source range. The kinds are lowImageResolution, declaredPixelsMismatch, rgbImage, thinRule, smallProcessText, inkLimit, safeZone and nearTrim. Without a transform a neutral counts one ink and any other colour three, and coverage is not checked; with one, the counts and the coverage are exact. The resolution of a picture is worked out from the pixels its resource declares, or from the file's own when imageSize(fileId) gives them (bitmapInfo on the bytes, or the decoded image): a declaration more than a pixel away from the file is reported once as declaredPixelsMismatch, a warning when it claims more pixels than the file has. placedImageResolutions(doc, { resources, imageSize }) lists every placed bitmap with its effective ppi, whether the preflight is on or not. The labels of a figure count as text for smallProcessText, inkLimit and safeZone.

import { bitmapInfo, outputTransform, parseIccProfile, preflightDocument, resolvePrintConfig } from 'postext';
import { inspectPrintMaster } from 'postext-pdf';
 
const print = resolvePrintConfig(config.print);
const transform = outputTransform(parseIccProfile(fogra51Bytes), { intent: print.renderingIntent });
const issues = preflightDocument(doc, {
  print,
  transform,
  resources,                                    // pixel sizes of the bitmaps
  imageSize: (fileId) => bitmapInfo(bytesOf(fileId)),  // the files' real pixels
  imageColor: (fileId) => colourOf(fileId),     // 'rgb' | 'cmyk' | 'gray', from the file
});
if (issues.some((i) => i.severity === 'critical')) process.exit(1);
 
const master = await inspectPrintMaster(masterBytes);
// => { nonEmbeddedFonts: ['Helvetica'], rgb: true, transparency: false }

#Reference implementation

The sandbox's PdfViewport component (packages/postext-sandbox/src/viewport/pdf/PdfViewport.tsx) wires the pieces above into a live preview with regenerate, download, and print buttons, and is a good starting point for any in-browser PDF integration. It builds the VDT through the shared layout worker (see Running layout in a Web Worker) so clicking Regenerate doesn't freeze the UI while the pipeline runs — the main thread only handles renderToPdf (which is already fast once the VDT exists).