Hyphenation
Hyphenation refers to the automated process of breaking words between lines to create a better visual consistency across a text block. This is a complex problem. It involves knowing about the language of the text, available space, ligatures, among other things.
React-pdf internally implements the Knuth and Plass line breaking algorithm that produces the minimum amount of lines without compromising text legibility. By default it's setup to hyphenate english words.
Other languages
Words are split with @react-pdf/hyphenate, a fast Liang hyphenation engine with an entry point per language, en-us being the default. To hyphenate another language, register its syllables function:
import { Font } from '@react-pdf/renderer';
import { syllables } from '@react-pdf/hyphenate/de';
Font.registerHyphenationCallback(syllables);Every language shipped by hyphen is available under the same name (de, es, fr, ru, zh-latn-pinyin, and 80+ more). Each language is its own entry point, so bundlers only include the patterns you actually import.
Custom callback
If you need more fine-grained control over how words break, you can pass your own callback and handle all that logic by yourself:
import { Font } from '@react-pdf/renderer'
const hyphenationCallback = (word, fallback) => {
// Return word parts in an array
}
Font.registerHyphenationCallback(hyphenationCallback);The second argument is the built-in splitter, so you can tweak its output instead of starting from scratch.
Protip: If you don't want to hyphenate words at all, just provide a callback that returns the same words it receives. More information here
Breaking without a hyphen
By default, a hyphen is added at the end of the line whenever a word breaks between two of its parts. Parts that already end with - don't get a second one, so blue-green breaks as blue- / green.
To break a word without adding a hyphen, return { string, hyphen: null } parts instead of strings. This is useful for URLs, file paths or long identifiers:
Font.registerHyphenationCallback((word, fallback) => {
if (word.startsWith('http')) {
return word.split(/(?<=[/.])/).map((string) => ({ string, hyphen: null }));
}
return fallback(word);
});Strings and parts can be mixed, so you decide part by part. hyphen can be '-' or null:
const hyphenationCallback = () => [
{ string: 'blue', hyphen: '-' },
{ string: 'ish', hyphen: null },
'green',
];Returning a plain array of strings works as before.
Chinese and Japanese
Chinese and Japanese text has no spaces between words, and lines may break between any two ideographs without a hyphen. React-pdf does this by default for Han, Hiragana, Katakana and Bopomofo text. Numbers and punctuation stay with the character they follow, so lines don't start with 。 or 、.
Your custom callback also receives these words. Plain strings it returns never get a hyphen in those scripts, unless a part explicitly sets hyphen: '-'.