Birch UI v0.1
Pricing

PDF export and printDocument

Print the pages you see, export a tagged vector PDF with embedded font subsets in the browser, and render documents to PDF on a server with Birch UI Document Editor.

Open .md

The editor has laid the document out into pages already, so printing and PDF export reuse that layout instead of asking the browser to paginate again.

Print#

TypeScript
editor.print(); // also Ctrl+P inside the editor and Layout → Print
const html = editor.getPrintHtml(); // the print document as a string

The print document holds one fixed-size box per layout page, with the same line breaks, headers, footers, page numbers, footnotes and watermark, and a CSS @page size for each section. print() loads it into a hidden frame and opens the browser's print dialog, where the user prints or saves a PDF.

Because every page is a box of the exact paper size, the printed page count equals getPageCount(). The test suite prints the demo documents with headless Chrome and compares the two numbers.

getPrintHtml() is useful for server-side rendering: give the string to headless Chrome (page.setContent(html) then page.pdf({ preferCSSPageSize: true, printBackground: true })) to get a PDF drawn with the real fonts.

Vector PDF in the browser#

TypeScript
const blob = await editor.exportPdf({
  title: 'Master Services Agreement',
  author: 'Priya Raman',
  fontLoader: async (family, { bold, italic }) => {
    const response = await fetch(`/fonts?family=${encodeURIComponent(family)}&bold=${bold}&italic=${italic}`);
    return response.ok ? response.arrayBuffer() : null;
  },
  onProgress: (page, pages) => setProgress(page / pages),
});

exportPdf reads the position of every word, rule, border, shading, shape and picture from the laid-out pages and writes a PDF file itself. It needs the page layout (it rejects in web layout). It waits for a layout pass that is still running, so there is no need to call whenLayoutReady() first. No print dialog is involved and nothing leaves the page unless your fontLoader fetches something. The result is a vector PDF: text can be selected and searched, links work, and the headings become PDF bookmarks.

Option Meaning
title, author, subject, keywords Document information. Defaults come from the document properties.
fonts PdfFontSource entries for this export; they replace the pdfFonts option.
fontLoader (family, { bold, italic }) => Promise<ArrayBuffer | Uint8Array | null>. Called once per family and style that has no registered font. Return null when you have no such font.
localFonts true asks the browser for the fonts installed on the computer (Local Font Access API, Chromium only, shows a permission prompt). Left out, installed fonts are used only when the permission was granted before. false never uses them.
tagged false leaves out the structure tree.
pdfA true adds the PDF/A identification and an sRGB output intent (see below).
compress false writes uncompressed streams.
outline false leaves out the heading outline.
onProgress Called once per page.

layoutToPdf(layout, options) is the DOM-free writer behind it. It takes a PdfDocumentLayout (pages with positioned text runs, lines, rectangles, paths, images and groups) and also runs in Node.js.

Fonts#

A PDF needs font data. The export looks for each font family in this order:

  1. fonts registered with the pdfFonts option or passed as fonts,
  2. the fontLoader callback,
  3. the fonts installed on the computer, when the browser has the Local Font Access API and the user allowed it,
  4. the standard Helvetica, Times and Courier families.

A family is also satisfied by a metric-compatible substitute: a font with the same advance widths, so text breaks at the same places. Registering Carlito under its own name is enough for text set in Calibri.

Document font Accepted substitutes
Calibri Carlito
Cambria Caladea
Arial, Helvetica Liberation Sans, Arimo
Arial Narrow Liberation Sans Narrow
Times New Roman, Times Liberation Serif, Tinos
Courier New, Courier Liberation Mono, Cousine
Georgia Gelasio
Segoe UI Selawik

The table works in both directions and is exported as FONT_SUBSTITUTIONS; fontSubstitutes(family) and fontFamilyStack(family) read it. The editor uses the same table for the fonts it draws with: text in Calibri is drawn with Calibri, Carlito.

registerFonts(fonts) makes font files available to every PDF written afterwards, in the browser and on a server, in addition to pdfFonts and fonts; clearRegisteredFonts() removes them.

TypeScript
import { registerFonts } from '@birchui/document/pdf';

registerFonts([
  { family: 'Carlito', data: regular },
  { family: 'Carlito', data: bold, bold: true },
]);

When a font is missing. Page counts depend on fonts, so the library says when one is missing instead of falling back silently:

  • The editor checks the fonts of the document (the default font, the fonts of its styles and of its text) after the document is set and fires fontsMissing with { fonts: [{ family, substitute }] }. substitute is the installed metric-compatible font that is drawn instead, or null; for null it also logs one warning, because lines and pages can then break differently than in Word. isFontAvailable(family) replaces the built-in check, which compares the width of a test string against the generic fallbacks.
  • renderDocumentPdf returns missingFonts and one warning per family that had neither a font file nor a substitute.
  • pdfA: true throws PdfFontError (code: 'pdfa-fonts-missing', families) when any text would use a standard font.

A CSS font list such as Calibri, Carlito, sans-serif is tried from left to right until the characters in use are covered, so a fontLoader can answer for Carlito when it has no Calibri. Generic names (serif, sans-serif, monospace) are passed to the loader too.

TypeScript
createDocumentEditor(host, {
  pdfFonts: [
    { family: 'Source Sans 3', data: regular },
    { family: 'Source Sans 3', data: bold, bold: true },
  ],
});

Embedded fonts are subsets. Only the glyphs the document uses are written:

  • TrueType outlines (.ttf, and TrueType faces in a .ttc collection) are rebuilt with new glyf, loca, hmtx, head, hhea and maxp tables, the parts of composite glyphs, the hinting programs and correct checksums. Carlito Regular is 628 kB; a subset for one page of English text is about 10 kB.
  • OpenType fonts with CFF outlines (.otf, and the faces of a .ttc such as Noto Sans CJK) are rebuilt as a CID-keyed CFF font that holds only the used glyph programs and the subroutines they call. The 15.4 MB CFF table of Noto Sans CJK SC becomes about 80 kB for forty glyphs.
  • Every embedded font is a Type 0 font with Identity-H encoding, a width array and a ToUnicode map, so copy, search and text extraction return the original characters.

Limits you should know about:

  • WOFF and WOFF2 files are not read. Supply the .ttf, .otf or .ttc file.
  • Variable fonts are embedded at their default instance. CFF2 outlines are rejected.
  • Bold and italic are never synthesized. When no bold face is supplied, bold text is drawn with the regular face.
  • Without any font for a family, the text is drawn with a standard font and each word is scaled to the width it has on screen. Line and page breaks stay exact, letter shapes differ, and only Windows-1252 characters can be written. A character that no supplied font contains is replaced with a placeholder and reported with console.warn.
  • Words are placed at their measured position. Kerning inside a word is spread evenly over the word instead of pair by pair.

Chinese, Japanese, Korean, Arabic and Hebrew#

The browser has already shaped and positioned the text, so the export measures each grapheme cluster of such a word and places its glyphs at the same coordinates. This keeps justified CJK lines and mixed left-to-right and right-to-left lines exactly as on screen.

  • CJK: one glyph per character through the font's character map.
  • Arabic: the joining form of each letter (isolated, initial, medial, final) is computed from its neighbours and taken from the font's GSUB single substitutions (isol, init, medi, fina), with the Arabic Presentation Forms of the character map as a fallback. Lam followed by alef becomes the lam-alef ligature (rlig, or the presentation form).
  • Hebrew: no shaping is needed; letters are placed right to left.
  • Glyphs are written in visual order and mapped back to the source characters, so pdftotext returns the logical text. The lam-alef ligature maps to its compatibility character (U+FEFB and its relatives); normalise with NFKC to get the two letters.

What is not done:

  • No GPOS positioning. Arabic and Hebrew vowel marks are placed approximately (centred on their base letter where the font gives glyph bounds) instead of on the font's anchors.
  • No other OpenType features: contextual alternates, discretionary ligatures and kashida justification are not applied. A font that only joins letters through contextual lookups falls back to presentation forms, or to isolated letters when it has none.
  • Scripts that reorder or merge glyphs (Devanagari and other Indic scripts, Thai vowel placement, Khmer) are written character by character and will look wrong.
  • A bracket inside a right-to-left run is drawn mirrored, and text extraction returns the mirrored character.
  • Some extractors print punctuation next to a right-to-left word before the word.

What is drawn#

Text with underline, strike-through and highlight; paragraph borders and shading; table borders and cell shading, with header rows repeated on following pages; pictures, also rotated, flipped and cropped; shapes (rectangle, rounded rectangle, ellipse, callout, lines and arrows) with fill, outline and their text; text watermarks with rotation and transparency; labels of bulleted, numbered and multilevel lists; headers and footers with page numbers; footnotes; column rules; the dotted leaders of a table of contents.

Links are real PDF links: web and mail addresses open, a link to #bookmark jumps to that bookmark, and the entries of a table of contents jump to their heading.

Not drawn, or approximated:

  • Shadows, gradients and double borders. Dashed and dotted borders use a fixed dash pattern.
  • Pictures that are not PNG or JPEG, charts and other embedded objects are written as bitmaps.
  • The watermark is drawn below the page content. On screen it lies above pictures.
  • The comments margin, change bars, the selection and spelling marks are left out. Tracked insertions and deletions are exported the way they are displayed.

Tagged PDF#

The file carries a structure tree, so screen readers and reflow can follow it: Document with P, H1 to H6, BlockQuote, L › LI › Lbl and LBody, Table › TR › TH and TD, TOC › TOCI, Figure with the picture's alternative text, Link with its annotation, and Note for footnotes. Headers, footers, watermarks and repeated table header rows are marked as pagination artifacts; borders and shading as layout artifacts. The catalog has /MarkInfo, /Lang (from the lang attribute of the host page) and /ViewerPreferences << /DisplayDocTitle true >>.

The tagging follows PDF 1.7 but has not been checked with a PDF/UA validator. Known gaps: table header cells have no scope or IDs, a footnote reference is not connected to its note, and runs in another language are not marked.

Metadata and PDF/A#

Every file has an XMP metadata stream (dc:title, dc:creator, dc:description, pdf:Producer, pdf:Keywords, creation and modification dates) that matches the document information dictionary.

pdfA: true adds what PDF/A-2b asks for on top of that: pdfaid:part 2 and pdfaid:conformance B in the XMP packet, and an sRGB output intent with an ICC profile that the library generates. The export then fails with PdfFontError when a font is not embedded, because PDF/A does not allow the standard fonts without font data; the error lists the families.

This output is PDF/A-oriented, not certified. It has not been run through veraPDF or another validator, CMYK JPEG pictures are passed through although the output intent is RGB, and you remain responsible for supplying every font. Validate the files yourself before you archive them as PDF/A.

Text effects in PDF#

Both PDF exports draw the effects of the Font dialog: all capitals, small capitals (capitals at four fifths of the size), single, double, thick, dotted, dashed, dot-dash and wavy underlines in their own colour, strikethrough and double strikethrough. The text itself is not changed: an all-capitals run is still stored, searched and exported to DOCX in the case it was typed in.

PDF on a server#

TypeScript
import { documentToPdf, docxToDocument } from '@birchui/document/headless';
import { readFile, writeFile } from 'node:fs/promises';

const data = await docxToDocument(await readFile('agreement.docx'));
const pdf = await documentToPdf(data, {
  fonts: [{ family: 'Calibri', data: new Uint8Array(await readFile('fonts/Carlito-Regular.ttf')) }],
});
await writeFile('agreement.pdf', pdf);

documentToPdf(data, options) lays a document model out without a browser and returns the PDF bytes. renderDocumentPdf also returns the warnings, the page count and missingFonts, and layoutDocument returns the layout tree. Options are those of the writer (compress, pdfA, tagged, creationDate, producer) plus fonts, title, author, subject, keywords, language and outline.

It measures text with the metrics of the fonts you pass or registered, or with the built-in Helvetica, Times and Courier metrics, and breaks lines itself. Pages, columns, widows and orphans, keep-with-next, footnotes and section starts are then decided by paginate, the same pagination engine the editor runs; only the measuring differs (font metrics here, the browser there). It supports:

  • paragraphs with the built-in styles and the styles of the document (styles: font, size, bold, italic, colour, indents, spacing, tabs, keep-with-next, page break before), alignment including justification, spacing that collapses between paragraphs, indents and keepWithNext,
  • tab stops with left, centre, right and decimal alignment and dot, hyphen, underscore and middle-dot leaders; default tab stops from the document settings,
  • runs with bold, italic, underline, strike-through, colour, size, font family, highlight, superscript, subscript and links,
  • bulleted, numbered and nested lists and Word numbering with the labels of numberingLabels, the indent and hanging indent of each numbering level, and the spacing of paragraphs inside list items,
  • sections with their own page size, orientation and margins, starting on the next page, continuously, or on an odd or even page; equal-width columns with a separator line, balanced before a continuous section break,
  • headers and footers per section, a different first page per section, different odd and even pages, page number and page count fields, page numbers that restart,
  • tables with borders, cell shading, column widths, merged cells and wrapped cell text; a row whose deletion is tracked is left out, like the text of a tracked deletion,
  • page breaks, widow and orphan control (two lines), footnotes at the foot of the page, PNG and JPEG pictures given as data URLs, text watermarks, a stored table of contents,
  • the outline, tags and metadata described above.

Agreement. With Carlito and Caladea supplied, the 12 documents of the independent review give these page counts (test/pdf-layout-agreement.test.ts, e2e/tests/document-layout-agreement.spec.ts):

Document LibreOffice Editor (Chrome) documentToPdf
01-contract (legal numbering, cross-references) 7 7 7
02-report (sections, landscape page, footnotes) 8 9 8
03-invoice 1 1 1
04-newsletter (continuous two-column section) 3 3 3
05-form 1 1 1
06-review (tracked changes) 1 1 1
07-rtl-cjk 1 1 1
08-long (202 to 204 pages, 60 tables) 203 202 204
09-article 1 1 1
10-memo 2 2 2
11-merge-template 1 1 1
12-styles (tab leaders, custom styles) 7 7 7

The editor matches LibreOffice for 10 of 12 and documentToPdf for 11 of 12; the editor and documentToPdf agree with each other for 10 of 12. Without the fonts documentToPdf measures with Helvetica and Times metrics and the long document comes out at 198 pages, which is why a missing font is reported.

Its limits:

  • It shares the pagination engine with the editor, not the line breaker: the editor's lines come from the browser, these from font metrics. Line breaks can differ by a word, and the page count by a page on long documents, as the table shows.
  • Columns of unequal width are laid out with equal widths. Line numbers and page borders are not drawn.
  • Lines break at spaces and between CJK characters. There is no hyphenation and there are no line-breaking rules for CJK punctuation.
  • A table row never splits across pages, header rows are not repeated, and a cell that spans rows does not make its rows taller. A footnote that does not fit is drawn whole on the page of its reference.
  • Right-to-left paragraphs run their words from right to left with joined Arabic letters, but lines that mix directions are not reordered by the bidirectional algorithm.
  • Pictures are placed in the line. Text wrapping, rotation and cropping are ignored, pictures that are not data URLs are left out with a warning, and shapes are not drawn.
  • Endnotes are placed like footnotes. A table of contents shows the page numbers stored in the document. Comments and tracked deletions are left out.

On a laptop the writer needs about 2 ms for a short contract; node packages/document/scripts/headless-throughput.mjs measures the whole DOCX-to-PDF pipeline on your machine.

When the PDF must look exactly like the editor, render getPrintHtml() with headless Chrome instead.

↑ ↓ to move, Enter to open, Esc to close