Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/six-paws-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@react-pdf/textkit": minor
"@react-pdf/layout": minor
"@react-pdf/stylesheet": minor
"@react-pdf/types": minor
---

Add support for fontFeatureSettings to customize ligatures, tabular number display, and other font features.
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/* eslint react/prop-types: 0 */
/* eslint react/jsx-sort-props: 0 */

import { Document, Font, Page, StyleSheet, Text } from '@react-pdf/renderer';
import React from 'react';

import RobotoFont from '../../../public/Roboto-Regular.ttf';
import RubikFont from '../../../public/Rubik-Regular.ttf';

const styles = StyleSheet.create({
body: {
paddingTop: 35,
paddingBottom: 45,
paddingHorizontal: 35,
position: 'relative',
fontSize: 14,
},
headline: {
fontFamily: 'Roboto',
fontSize: '24',
paddingVertical: 12,
},
rubik: {
fontFamily: 'Rubik',
},
roboto: {
fontFamily: 'Roboto',
},
tabular: {
fontFeatureSettings: ['tnum'],
},
smallCapitals: {
fontFeatureSettings: ['smcp'],
},
disableCommonLigatures: {
fontFeatureSettings: { liga: 0 },
},
});

Font.register({
family: 'Rubik',
fonts: [{ src: RubikFont, fontWeight: 400 }],
});
Font.register({
family: 'Roboto',
fonts: [{ src: RobotoFont, fontWeight: 400 }],
});

const MyDoc = () => {
const longNumberExample = "012'345'678'901";
const commonLigaturesExample = 'A firefighter from Sheffield';
return (
<Page style={styles.body}>
<Text style={styles.headline}>Rubik</Text>
<Text style={styles.rubik}>{longNumberExample} – Default features</Text>
<Text style={[styles.rubik, styles.tabular]}>
{longNumberExample} – Tabular numbers
</Text>
<Text style={styles.headline}>Roboto</Text>
<Text style={styles.roboto}>
{commonLigaturesExample} – Default features
</Text>
<Text style={[styles.roboto, styles.disableCommonLigatures]}>
{commonLigaturesExample} – Common ligatures off
</Text>
<Text style={[styles.roboto, styles.smallCapitals]}>
{commonLigaturesExample} – Small capitals
</Text>
</Page>
);
};

const FontFeatureSettings = () => {
return (
<Document>
<MyDoc />
</Document>
);
};

export default {
id: 'font-feature-settings',
name: 'Font Feature Settings',
description: '',
Document: FontFeatureSettings,
};
2 changes: 2 additions & 0 deletions packages/examples/vite/src/examples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import duplicatedImages from './duplicated-images';
import ellipsis from './ellipsis';
import emoji from './emoji';
import fontFamilyFallback from './font-family-fallback';
import fontFeatureSettings from './font-feature-settings';
import fontWeight from './font-weight';
import goTo from './go-to';
import imageBackground from './image-background';
Expand Down Expand Up @@ -34,6 +35,7 @@ const EXAMPLES = [
emoji,
fontFamilyFallback,
fontWeight,
fontFeatureSettings,
goTo,
JpgOrientation,
knobs,
Expand Down
1 change: 1 addition & 0 deletions packages/layout/src/steps/resolveInheritance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const BASE_INHERITABLE_PROPERTIES = [
'fontSize',
'fontStyle',
'fontWeight',
'fontFeatureSettings',
'letterSpacing',
'opacity',
'textDecoration',
Expand Down
1 change: 1 addition & 0 deletions packages/layout/src/svg/inheritProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const BASE_SVG_INHERITED_PROPS = [
'fontSize',
'fontStyle',
'fontWeight',
'fontFeatureSettings',
'letterSpacing',
'opacity',
'textDecoration',
Expand Down
17 changes: 17 additions & 0 deletions packages/layout/src/text/getAttributedString.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as P from '@react-pdf/primitives';
import { Fragment, fromFragments } from '@react-pdf/textkit';
import FontStore from '@react-pdf/font';
import type { FontFeatureSettings } from '@react-pdf/stylesheet';

import { embedEmojis } from './emoji';
import ignoreChars from './ignoreChars';
Expand All @@ -24,6 +25,20 @@ const isRasterImage = (node: SafeImageNode): boolean =>
const isTextInstance = (node: SafeNode): node is SafeTextInstanceNode =>
node.type === P.TextInstance;

const transformFontFeatureSettings = (
fontFeatureSettings?: FontFeatureSettings,
): string[] | Record<string, boolean> | undefined => {
if (!fontFeatureSettings) return undefined;
if (Array.isArray(fontFeatureSettings)) return fontFeatureSettings;

return Object.fromEntries(
Object.entries(fontFeatureSettings).map(([key, value]) => [
key,
value !== 0,
]),
);
};

/**
* Get textkit fragments of given node object
*
Expand All @@ -50,6 +65,7 @@ const getFragments = (
fontWeight,
fontStyle,
fontSize = 18,
fontFeatureSettings,
textAlign,
lineHeight,
textDecoration,
Expand Down Expand Up @@ -103,6 +119,7 @@ const getFragments = (
// @ts-expect-error allow this props access
link: parentLink || instance.props?.src || instance.props?.href,
align: textAlign || (direction === 'rtl' ? 'right' : 'left'),
features: transformFontFeatureSettings(fontFeatureSettings),
};

for (let i = 0; i < instance.children.length; i += 1) {
Expand Down
4 changes: 4 additions & 0 deletions packages/layout/tests/steps/resolveInhritance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,8 @@ describe('layout resolveInheritance', () => {
test('Should inherit textAlign value', shouldInherit('textAlign'));
test('Should inherit visibility value', shouldInherit('visibility'));
test('Should inherit wordSpacing value', shouldInherit('wordSpacing'));
test(
'Should inherit fontFeatureSettings value',
shouldInherit('fontFeatureSettings'),
);
});
40 changes: 40 additions & 0 deletions packages/layout/tests/text/getAttributedString.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, expect, test } from 'vitest';
import FontStore from '@react-pdf/font';
import type { FontFeatureSettings } from '@react-pdf/stylesheet';

import getAttributedString from '../../src/text/getAttributedString';
import { SafeTextNode } from '../../src/types';

const font = {};

const fontStore = {
getFont: () => ({ data: font }),
} as unknown as FontStore;

const getTextNode = (fontFeatureSettings: FontFeatureSettings): SafeTextNode =>
({
type: 'TEXT',
props: {},
style: { fontFeatureSettings },
children: [{ type: 'TEXT_INSTANCE', value: 'Lorem' }],
}) as SafeTextNode;

describe('getAttributedString', () => {
test('should map numeric font feature settings to boolean features', () => {
const result = getAttributedString(
fontStore,
getTextNode({ liga: 0, kern: 1 }),
);

expect(result.runs[0].attributes.features).toEqual({
liga: false,
kern: true,
});
});

test('should preserve font feature setting arrays', () => {
const result = getAttributedString(fontStore, getTextNode(['tnum']));

expect(result.runs[0].attributes.features).toEqual(['tnum']);
});
});
35 changes: 34 additions & 1 deletion packages/stylesheet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ type Style = {
fontSize?: number | string;
fontStyle?: 'normal' | 'italic' | 'oblique';
fontWeight?: FontWeight;
fontFeatureSettings?: FontFeatureSettings;
letterSpacing?: number | string;
lineHeight?: number | string;
textAlign?: 'left' | 'right' | 'center' | 'justify';
Expand Down Expand Up @@ -543,7 +544,7 @@ type Transform =
};
```

### FontWeight
### FontWeight & FontFeatureSettings

```ts
type FontWeight =
Expand All @@ -562,6 +563,38 @@ type FontWeight =
| 'extrabold'
| 'heavy'
| 'black';

type FontFeatureSetting =
| 'liga'
| 'dlig'
| 'onum'
| 'lnum'
| 'tnum'
| 'zero'
| 'frac'
| 'sups'
| 'subs'
| 'smcp'
| 'c2sc'
| 'case'
| 'hlig'
| 'calt'
| 'swsh'
| 'hist'
| `ss${'01' | '02' | '03' | '04' | '05' | '06' | '07' | '08' | '09' | '10' | '11' | '12' | '13' | '14' | '15' | '16' | '17' | '18' | '19' | '20'}`
| 'kern'
| 'locl'
| 'rlig'
| 'medi'
| 'init'
| 'isol'
| 'fina'
| 'mark'
| 'mkmk';

type FontFeatureSettings =
| FontFeatureSetting[]
| Partial<Record<FontFeatureSetting, number>>;
```

## License
Expand Down
33 changes: 33 additions & 0 deletions packages/stylesheet/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,12 +321,45 @@ export type TextTransform =

export type VerticalAlign = 'sub' | 'super';

export type FontFeatureSetting =
| 'liga'
| 'dlig'
| 'onum'
| 'lnum'
| 'tnum'
| 'zero'
| 'frac'
| 'sups'
| 'subs'
| 'smcp'
| 'c2sc'
| 'case'
| 'hlig'
| 'calt'
| 'swsh'
| 'hist'
| `ss${'01' | '02' | '03' | '04' | '05' | '06' | '07' | '08' | '09' | '10' | '11' | '12' | '13' | '14' | '15' | '16' | '17' | '18' | '19' | '20'}`
| 'kern'
| 'locl'
| 'rlig'
| 'medi'
| 'init'
| 'isol'
| 'fina'
| 'mark'
| 'mkmk';

export type FontFeatureSettings =
| FontFeatureSetting[]
| Partial<Record<FontFeatureSetting, number>>;

export type TextStyle = {
direction?: 'ltr' | 'rtl';
fontSize?: number | string;
fontFamily?: string | string[];
fontStyle?: FontStyle;
fontWeight?: FontWeight;
fontFeatureSettings?: FontFeatureSettings;
letterSpacing?: number | string;
lineHeight?: number | string;
maxLines?: number | string;
Expand Down
15 changes: 11 additions & 4 deletions packages/textkit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

> An advanced text layout framework

A comprehensive text layout engine for react-pdf. Handles complex text rendering including bidirectional text, line breaking, hyphenation, justification, font substitution, and text decoration.
A comprehensive text layout engine for react-pdf. Handles complex text rendering including bidirectional text, line breaking, hyphenation, justification, font substitution, OpenType font features, and text decoration.

## Acknowledges

Expand Down Expand Up @@ -46,7 +46,14 @@ const engines = {
// Create attributed string from fragments
const attributedString = fromFragments([
{ string: 'Hello ', attributes: { fontSize: 12, font: [myFont] } },
{ string: 'World!', attributes: { fontSize: 12, font: [myFont] } },
{
string: "012'345'678'901",
attributes: {
fontSize: 12,
font: [myFont],
features: ['tnum'],
},
},
]);

// Define container
Expand All @@ -70,7 +77,7 @@ The layout engine processes text through the following steps:
2. Get bidi runs and paragraph direction
3. Font substitution - map to resolved font runs
4. Script itemization
5. Font shaping - text to glyphs
5. Font shaping - text to glyphs, applying optional OpenType font features
6. Line breaking
7. Bidi reordering
8. Justification
Expand Down Expand Up @@ -234,7 +241,7 @@ type Attributes = {
characterSpacing?: number;
color?: string;
direction?: 'rtl' | 'ltr';
features?: unknown[];
features?: string[] | Record<string, boolean>;
fill?: boolean;
font?: Font[];
fontSize?: number;
Expand Down
4 changes: 2 additions & 2 deletions packages/textkit/src/layout/generateGlyphs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const layoutRun = (string: string) => {
*/
return (run: Run) => {
const { start, end, attributes = {} } = run;
const { font } = attributes;
const { font, features } = attributes;

if (!font)
return {
Expand All @@ -61,7 +61,7 @@ const layoutRun = (string: string) => {
// passing LTR To force fontkit to not reverse the string
const glyphRun = font[0].layout(
runString,
undefined,
features,
undefined,
undefined,
'ltr',
Expand Down
2 changes: 1 addition & 1 deletion packages/textkit/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export type Attributes = {
characterSpacing?: number;
color?: string;
direction?: 'rtl' | 'ltr';
features?: unknown[];
features?: string[] | Record<string, boolean>;
fill?: boolean;
font?: Font[];
fontSize?: number;
Expand Down
Loading
Loading