Fonts and non-Latin textPDF
Supply TrueType or OpenType fonts so saved free text, stamps, typed signatures and form values in Greek, Cyrillic, Hebrew, Arabic and other scripts are embedded as subset fonts that every PDF reader draws and extracts correctly.
The text that Birch UI PDF writes into a file (free text annotations, custom stamp labels, typed signatures, redaction overlay text and the appearance of text, combo and list fields) is drawn with the standard Helvetica and Times fonts by default. Those fonts only cover Western European text. To save any other script, supply one or more TrueType or OpenType fonts. The package never downloads fonts: you load the bytes.
Supplying fonts#
import { openPdfDocument } from '@birchui/pdf/engine';
const [sans, arabic] = await Promise.all(
['/fonts/NotoSans-Regular.ttf', '/fonts/NotoSansArabic-Regular.ttf'].map((url) =>
fetch(url).then((r) => r.arrayBuffer()),
),
);
const pdf = openPdfDocument(bytes, {
fonts: [
{ name: 'Noto Sans', data: new Uint8Array(sans) },
{ name: 'Noto Sans Arabic', data: new Uint8Array(arabic) },
],
});
pdf.addAnnotation({ type: 'freeText', pageIndex: 0, rect: [72, 640, 320, 700], text: 'Προς έγκριση έως 14/03' });
pdf.setFormValue('client.name', 'Ольга Кузнецова');
const { bytes: saved } = await pdf.save();fonts is an option of openPdfDocument and loadPdfDocument. Text added with addPageText, watermarks, headers, footers and Bates numbers use the same fonts. createFontRegistry(fonts) builds a registry by hand for the fonts option of a single addWatermark, addHeaderFooter, addBatesNumbers or addPageText call.
In the viewer#
createPdfViewer takes the same fonts list and passes it to its document session. Annotations, form values and text added or edited with the content tools are then embedded with those fonts when the file is saved:
import { createPdfViewer } from '@birchui/pdf';
declare const notoSans: Uint8Array;
const viewer = createPdfViewer(document.querySelector<HTMLElement>('#vertrag')!, {
document: bytes,
fonts: [{ name: 'Noto Sans', data: notoSans }],
});On screen the viewer draws annotations and form values with the browser's fonts, so every script is displayed with or without fonts. The option is read when a document is opened; changing it with update affects the next load.
What gets embedded#
- Only the glyphs a text actually uses are embedded. The subset keeps the original glyph ids, drops the outlines of every other glyph and carries a
ToUnicodemap, so search, copy andpdftotextreturn the characters you wrote. - A TrueType font (
glyfoutlines) is written as a Type 0 font with aCIDFontType2descendant,Identity-Hencoding, per-glyph widths and a font descriptor taken from the font's own metrics. Font programs are compressed. - An OpenType font with CFF outlines (most
.otffiles, including the Source Han and Noto CJK families) is written as aCIDFontType0descendant with aCIDFontType0Cprogram. The subset holds the charstrings of the glyphs used and the subroutines they call; unused subroutines are emptied, and a name-keyed font becomes CID-keyed.pdffontslists it as "CID Type 0C", embedded and subset. - When one glyph stands for two different texts, for example an alef that is the base of "أ" in one word and a plain "ا" in another, it gets a second character code so that each use extracts as the text you wrote.
- Text that fits the standard Windows Latin encoding keeps using the standard fonts, and the output is identical to what you get without the option. A file only grows when a supplied font is really needed.
- Identical subsets are shared inside one save; different texts get their own small subset.
Choosing a font for each run#
Text is split into runs by script (Latin, Greek, Cyrillic, Hebrew, Arabic, Devanagari, Thai, Hangul, Kana, Han). For each run the first font in fonts that has every character of the run is used, so order the list from most to least preferred. Spaces, digits and punctuation stay with the run next to them. If no single font covers a run, the choice falls back to one character at a time. A character that no supplied font contains is drawn with the missing-glyph box of the font in use, so make sure your list covers the scripts your users type. A common setup is one broad Latin, Greek and Cyrillic font followed by one font per additional script.
Right-to-left text#
Hebrew and Arabic are laid out right to left:
- The paragraph direction comes from the first strong character. Right-to-left runs are reversed into visual order, numbers and Latin words inside them stay left to right, and brackets are mirrored.
- Arabic letters are joined through the font's own OpenType tables when it has them: the
ccmp,locl,isol,init,medi,finaandrligfeatures of thearabscript are applied in that order, followed byrclt,caltandliga, so the lam-alef forms and other required ligatures come from the font. A font without these features (DejaVu Sans, for example) falls back to the Unicode presentation forms, as before. - Vowel marks and other combining marks are placed on their base letter with the font's
mark(mark-to-base) andmkmk(mark-to-mark) positioning. A positioned mark is drawn where the font says and its character is carried by an invisible copy on the baseline, sopdftotextand copy and paste return the vocalised word in logical order. - A free text annotation whose text starts right to left is right-aligned unless you set
textAlign. Form fields follow the field's own alignment. - The
ToUnicodemap points every glyph back at its logical characters, so extraction returns the text in reading order.
Chinese, Japanese and Korean#
Supply a font that covers the characters, TrueType or OpenType, and list it after your Latin font. Each ideograph, kana and Hangul syllable is one glyph, lines are wrapped between any two characters when there is no space, and only the characters used are embedded, so a 16 MB CJK font adds a few kilobytes per text. The tests of the package write Chinese, Japanese and Korean lines with a subset of Noto Sans CJK and compare what pdftotext returns with the input.
What shaping covers#
| Script | What is applied |
|---|---|
| Latin, Greek, Cyrillic, Armenian, Hebrew, Thai, Hangul, Kana, Han | ccmp, locl and rlig substitutions and mark positioning, when the font has them |
| Arabic | the same, plus joining forms and rclt, calt, liga |
| Devanagari and other Indic scripts, Khmer, Myanmar | nothing: these need reordering and are drawn character by character |
GSUB single, multiple, ligature, contextual and chained contextual lookups are read (types 1, 2, 4, 5, 6 and extensions); GPOS mark-to-base and mark-to-mark (types 4 and 6). Alternate substitution, reverse chaining, pair kerning, cursive attachment and mark-to-ligature positioning are not applied.
Limits#
- Fonts are TrueType (
.ttf) or OpenType with CFF outlines (.otf). WOFF and WOFF2 files, and variable fonts with CFF2 outlines, are rejected with a console warning and skipped; pass the uncompressed, static font. For a.ttcor.otccollection the first face is used. - Scripts that need reordering or conjunct formation, such as Devanagari, Bengali, Tamil, Khmer and Myanmar, are drawn character by character and will look wrong. Thai with stacked marks is positioned only as far as the font's mark tables go. Pair kerning and discretionary ligatures of Latin text are not applied. A mark on a ligature (a vowel on lam-alef) is placed on the ligature as a whole.
- Shaping was checked against the glyph choices and anchors of one font (a subset of Noto Sans Arabic) and by reading the text back with poppler; it was not compared with HarfBuzz, which was not available where this was built.
- The bidirectional layout is a simplified form of the Unicode algorithm: it has no explicit embedding or isolate controls and no bracket pairing. Typical labels, names, addresses and amounts come out right; heavily mixed-direction paragraphs can differ from a browser.
- Lines are wrapped at spaces before reordering. There is no vertical writing.
- The field's default appearance string (
/DA) still names Helvetica. A reader that regenerates field appearances itself, instead of using the saved ones, shows non-Latin values with its own fallback font. - Editing existing page text uses the fonts already in the page; see Content editing for when a supplied font is embedded instead.
Loading fonts on demand#
Supplying every font up front costs a download nobody may need. fontFallback is called when a save meets text that no supplied font and no standard font can draw, once per script, and what it returns is embedded as a subset like any other font:
import { openPdfDocument } from '@birchui/pdf/engine';
import { createFontPack } from '@birchui/pdf/fonts';
declare const bytes: Uint8Array;
const pack = createFontPack({
fonts: {
cyrillic: '/fonts/NotoSans-Regular.ttf',
greek: '/fonts/NotoSans-Regular.ttf',
arabic: '/fonts/NotoSansArabic-Regular.ttf',
hebrew: '/fonts/NotoSansHebrew-Regular.ttf',
han: '/fonts/NotoSansSC-Regular.ttf',
kana: '/fonts/NotoSansJP-Regular.ttf',
hangul: '/fonts/NotoSansKR-Regular.ttf',
default: '/fonts/NotoSans-Regular.ttf',
},
load: (url) => fetch(url).then((response) => response.arrayBuffer()),
});
const pdf = openPdfDocument(bytes, { fontFallback: pack.fontFallback });
pdf.setFormValue('client.name', 'Ольга Кузнецова');
const { bytes: saved } = await pdf.save();
console.info(saved.length);createFontPack({ fonts, load })maps scripts (latin,greek,cyrillic,armenian,hebrew,arabic,devanagari,thai,hangul,kana,han,other, anddefaultfor the rest) to the font files you serve. An entry is a URL, the bytes, or a function that returns them. The package does not fetch: URLs are passed to yourloadcallback, and each file is loaded once.pack.preload(scripts?)loads fonts ahead of time and returns them in the shape thefontsoption takes.pack.scriptsOf(text)andscriptsOfText(text)name the scripts of a text.fontFallback: (script, characters) => Uint8Array | { name, data } | undefined, onopenPdfDocument,loadPdfDocument,createPdfViewerandmailToPdf, is the plain callback behind it; write your own when a pack does not fit.pdf.loadFallbackFonts(text)asks it ahead of a save.- Chinese, Japanese and Korean text is laid out horizontally and wraps between any two characters. The fonts are large; a TrueType build of a regional Noto Sans font is 8 to 16 MB before subsetting, and the subset written to the file holds only the glyphs used.
@birchui/pdf/fontsalso exports the font code the package itself uses:parseTrueType,glyphAdvance,glyphData,glyphClosure,subsetTrueType,embedTrueTypeSubset,createFontRegistry,toVisual,shapeArabic,reorderVisual,detectScriptandparagraphDirection.
When no font can draw a character#
Saving a document never fails because a font is missing. Text that the standard fonts cannot draw goes through three steps, in this order:
- Supplied fonts.
fonts, thenfontFallbackor a font pack for the scripts that are still missing. The text is embedded as real, selectable text. - The fonts of the browser, in the viewer. A text box or callout, a stamp label, a typed signature or the value of a form field that still has characters without a font is drawn line by line on a canvas with the fonts of the browser, and that drawing is written into the appearance stream as a one-bit image mask in the text colour, at four pixels per point. Any reader shows it. The annotation keeps the real text in
/Contents(and in XFDF and JSON exports), so it stays searchable in the comments panel and editable later; the drawn appearance itself is not selectable text, and formatted text loses its bold, italic and colour runs in that appearance.textRasterizer: falseon the viewer turns the step off;textRasterizer: { measure, rasterize }onopenPdfDocumentor the viewer supplies your own, for example one backed bynode-canvason a server. - A report. Whatever is still left (in the headless engine, where there is no browser) is written as
?in the appearance, as the missing-glyph box when a supplied font is in use. The file is saved, the real text is still stored as Unicode in/Contentsor/V, thefontMissingevent fires with{ characters, scripts }, and the result ofsave()carries the same report inmissingGlyphs.
Form fields get the same three steps. A text, combo or list field value in another script is embedded with a supplied font; a rich-text field keeps its bold, italic and colour runs with a supplied font and is drawn as plain text when only the browser can draw it. The value always stays in /V (and the formatted value in /RV) as Unicode. When step 3 is reached for a form field, the file also asks readers to redraw the form with their own fonts (/NeedAppearances); it does not when the value was embedded or drawn as an image, because a reader that redraws would throw that appearance away.
The report is recoverable: every save writes the appearances of changed annotations and fields afresh, so supply a font for the named scripts and save the same document again.
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
declare function loadFontFor(script: string): Promise<Uint8Array | undefined>;
let isAsking = false;
const pdf = openPdfDocument(bytes, {
fontFallback: (script) => (isAsking ? loadFontFor(script) : undefined),
});
pdf.setFormValue('client.name', '東京物流株式会社');
let result = await pdf.save();
if (result.missingGlyphs) {
console.warn(`no font for ${result.missingGlyphs.scripts.join(', ')}`);
isAsking = true;
result = await pdf.save();
}allowMissingGlyphs: false, on a single save() or as an option of the document or the viewer, makes save() reject with a PdfMissingGlyphError instead of writing step 3; the error carries characters and scripts and the document stays unsaved. This was the default before, so set it if your code relies on the rejection.
Migration. Before this release save() rejected with PdfMissingGlyphError whenever text had no font, unless allowMissingGlyphs was true. The default is now the other way round. Code that relied on the rejection to stop a save, for example to ask the user for a font first, has to pass allowMissingGlyphs: false or check missingGlyphs on the result.
addWatermark, addHeaderFooter, addBatesNumbers, the comment summary as PDF and mailToPdf are unchanged: they refuse with a PdfMissingGlyphError unless allowMissingGlyphs: true is passed, and addPageText returns { ok: false, reason: 'missing-glyphs' }. Internal copies the viewer makes for its preview, printing and splitting do not fire the event.