# Welcome

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

## Want to jump right in?

{% content-ref url="/pages/smHG6ZWP8SQSzX4yXDRD" %}
[Quick Start](/quick-start)
{% endcontent-ref %}

## Want to deep dive?

{% content-ref url="/pages/z8uBTch5iqXVBobfAeKW" %}
[API Reference Index](/reference/api-reference-index)
{% endcontent-ref %}

***

{% content-ref url="/pages/vttesg905hu1e2ApYKJG" %}
[Fontkit Object](/reference/fontkit-object)
{% endcontent-ref %}

{% content-ref url="/pages/Z4tdcUzZTzUPsG5YQFpg" %}
[Font Object](/reference/font-object)
{% endcontent-ref %}

{% content-ref url="/pages/rvCYR99tjI9JaTfra4Eu" %}
[GlyphRun Object](/reference/glyphrun-object)
{% endcontent-ref %}

{% content-ref url="/pages/5Y8se3j3lAm5aqjvrz8e" %}
[Glyph Object](/reference/glyph-object)
{% endcontent-ref %}

{% content-ref url="/pages/QwnyEBegGFZsR4nqLHJe" %}
[Path Object](/reference/path-object)
{% endcontent-ref %}

{% content-ref url="/pages/z1zI5WG3INcAh2VWfo2S" %}
[Subset Object](/reference/subset-object)
{% endcontent-ref %}


# Quick Start

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

## Installation

Install via NPM:

```bash
npm install fontkit
```

## Load a font

{% tabs %}
{% tab title="ES6 (Browser)" %}

```python
import * as fontkit from 'fontkit';

async function loadFont(url) {
  const response = await fetch(url);
  const arrayBuffer = await response.arrayBuffer();
  const buf = new Uint8Array(arrayBuffer);
  const font = fontkit.create(buf);
  console.log(font)
}
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
var fontkit = require('fontkit');

// open a font synchronously
var font = fontkit.openSync('font.ttf');
```

{% endtab %}
{% endtabs %}

## Layout a line of text

```javascript
const run = font.layout('Hello World!');
```

```javascript
const run = font.layout('Hello World!', {
  dlig: true,
  swsh: false,
  pcap: false
});
```

## Get pathData of a `GlyphRun`

```javascript
let pathData = '';
let x = 0;
let y = 0;
run.glyphs.forEach((glyph, index) => {
  const position = run.positions[index];
  if (glyph.path) {
    pathData += glyph.path
      .scale(1, -1)
      .translate(x + position.xOffset, y + position.yOffset)
      .toSVG();
    x += position.xAdvance;
    y += position.yAdvance;
  }
});
console.log(pathData);
```


# API Reference Index

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

## **Fontkit Object**

{% content-ref url="/pages/vttesg905hu1e2ApYKJG" %}
[Fontkit Object](/reference/fontkit-object)
{% endcontent-ref %}

* `fontkit.openSync(filePath, postscriptName)` Opens a font file synchronously and returns a font object.
* `fontkit.open(filePath, postscriptName, callback)` Opens a font file asynchronously.
* `fontkit.create(buffer, postscriptName)` Creates a new font object from a buffer.

## **Font Object**

{% content-ref url="/pages/Z4tdcUzZTzUPsG5YQFpg" %}
[Font Object](/reference/font-object)
{% endcontent-ref %}

* `font.layout(string)` Layouts the given string with the font and returns a GlyphRun object.
* `font.glyphForCodePoint(codePoint)` Gets a glyph for a given Unicode code point.
* `font.hasGlyphForCodePoint(codePoint)` Checks if the font has a glyph for the given code point.
* `font.characterSet` Returns the set of Unicode code points supported by the font.
* `font.availableFeatures` Returns the list of OpenType feature tags available in the font.

## **GlyphRun Object**

{% content-ref url="/pages/rvCYR99tjI9JaTfra4Eu" %}
[GlyphRun Object](/reference/glyphrun-object)
{% endcontent-ref %}

* `glyphRun.glyphs` An array of Glyph objects in the run.
* `glyphRun.positions` An array of position objects for each glyph.

## **Glyph Object**

{% content-ref url="/pages/5Y8se3j3lAm5aqjvrz8e" %}
[Glyph Object](/reference/glyph-object)
{% endcontent-ref %}

* `glyph.path` Returns a Path object representing the glyph’s outline.
* `glyph.bbox` Gets the glyph’s bounding box, i.e., the rectangle that encloses the glyph’s outline.
* `glyph.cbox` Gets the glyph’s control bounding box.
* `glyph.advanceWidth` The advance width of the glyph.

## **Path Object**

{% content-ref url="/pages/QwnyEBegGFZsR4nqLHJe" %}
[Path Object](/reference/path-object)
{% endcontent-ref %}

* `path.moveTo(x, y)` Moves the pen to a new location.
* `path.lineTo(x, y)` Draws a straight line to a new location.
* `path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)` Draws a cubic bezier curve.
* `path.quadraticCurveTo(cpx, cpy, x, y)` Draws a quadratic bezier curve.
* `path.closePath()` Closes the current path.
* `path.bbox` Returns the bounding box of the path.

## Subset Object

{% content-ref url="/pages/z1zI5WG3INcAh2VWfo2S" %}
[Subset Object](/reference/subset-object)
{% endcontent-ref %}

* `subset.includeGlyph(glyph)` Includes the given glyph in the subset.
* `subset.encode()` Encodes the subset font.


# Fontkit Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

The main `fontkit` object is the entry point to the library and provides methods for opening and reading font files. Here's a detailed look at the `fontkit` object's methods and properties:

## **Methods**:

### `fontkit.openSync(filePath, postscriptName)`

* **Description**: Opens a font file synchronously and returns a `Font` object.
* **Parameters**:
  * `filePath`: The path to the font file.
  * `postscriptName`: (Optional) The specific font to load in case the file contains multiple fonts.

### `fontkit.open(filePath, postscriptName, callback)`

* **Description**: Opens a font file asynchronously.
* **Parameters**:
  * `filePath`: The path to the font file.
  * `postscriptName`: (Optional) The specific font to load in case the file contains multiple fonts.
  * `callback`: Function to be called once the font is loaded. It follows the typical node callback pattern where the first argument is an error, and the second is the resulting `Font` object.

### `fontkit.create(buffer, postscriptName)`

* **Description**: Creates a new `Font` object from a buffer. This is useful if you've already read the font file into memory or if you're retrieving it from a source other than the file system.
* **Parameters**:
  * `buffer`: A buffer containing the font data.
  * `postscriptName`: (Optional) The specific font to load in case the buffer contains multiple fonts.

## **Properties**:

The primary interactions with the `fontkit` object are through the methods listed above. There aren't specific notable properties directly on the `fontkit` object itself; most of the functionality and properties you'd interact with are on the objects it returns (like the `Font` object).

## **Supported Font Formats**:

Fontkit is known for its comprehensive support for different font formats. While this isn't directly a method or property on the `fontkit` object, it's worth noting that Fontkit supports formats like:

* TrueType (`ttf`)
* OpenType (`otf`)
* WOFF & WOFF2
* TrueType Collection (`ttc`)
* Datafork TrueType Suite (`dfont`)
* And more...

## **Use fontkit in browser context**:

```
npm install fontkit
```

```javascript
import * as fontkit from 'fontkit';

const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const buf = new Uint8Array(arrayBuffer);
const font = fontkit.create(buf);
```


# Font Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

The Font object is central to Fontkit. It represents a font in your system or a font file.

## Properties (Read-only)

### `font.postscriptName`:

* **Description**: The PostScript name of the font. This is a unique identifier, often used in CSS and other contexts.
* **Type**: String

### `font.fullName`:

* **Description**: The full name of the font, typically including its weight or style.
* **Type**: String

### `font.familyName`:

* **Description**: The name of the font family to which this font belongs.
* **Type**: String

### `font.subfamilyName`:

* **Description**: The specific style or weight of the font within its family (e.g., "Bold" or "Italic").
* **Type**: String

### `font.copyright`:

* **Description**: The copyright statement associated with the font.
* **Type**: String

### `font.version`:

* **Description**: The version string of the font.
* **Type**: String

***

### `font.numGlyphs`:

* **Description**: The total number of glyphs in the font.
* **Type**: Number

### `font.characterSet`:

* **Description**: A set of all Unicode characters covered by the font.
* **Type**: Set of Numbers

### `font.availableFeatures`:

* **Description**: A list of OpenType feature tags available in the font.
* **Type**: Array of Strings

***

### `font.unitsPerEm`:

* **Description**: The number of font units per em. It's a foundational metric for a font, often set to values like 1000 or 2048.
* **Type**: Number

### `font.ascent`:

* **Description**: The font's ascent, which is the distance from the baseline to the top of the font's bounding box.
* **Type**: Number

### `font.descent`:

* **Description**: The font's descent, which is the distance from the baseline to the bottom of the font's bounding box.
* **Type**: Number

### `font.capHeight`:

* **Description**: The height of capital letters from the baseline.
* **Type**: Number

### `font.xHeight`:

* **Description**: The height of lowercase letters, specifically the height of the letter 'x'.
* **Type**: Number

### `font.lineGap`:

* **Description**: The recommended line gap or spacing between lines of text for this font.
* **Type**: Number

### `font.underlinePosition`:

* **Description**: The position of the underline relative to the baseline.
* **Type**: Number

### `font.underlineThickness`:

* **Description**: The thickness of the underline.
* **Type**: Number

### `font.italicAngle`:

* **Description**: The angle (in degrees) of the italic slant. Upright fonts have an italic angle of 0.
* **Type**: Number

### `font.bbox`:

* **Description**: The font's bounding box, which encompasses all glyphs in the font. It's an object with `minX`, `minY`, `maxX`, and `maxY` properties.
* **Type**: Object

***

### `font.variationAxes`:

* **Description**: Information about variable font axes if the font is a variable font. Each axis has properties like `tag`, `name`, `min`, `default`, and `max`.
* **Type**: Array of Objects

### `font.namedVariations`:

* **Description**: Named instances for variable fonts, such as predefined width or weight variations.
* **Type**: Object

***

### `font._cmapProcessor`:

* **Description**: An internal processor for the font's character map. Typically used internally by Fontkit.
* **Type**: Object

### `font._layoutEngine`:

* **Description**: An internal engine for glyph layout. Typically used internally by Fontkit.
* **Type**: Object

### `font._variationProcessor`:

* **Description**: An internal processor for handling font variations. Typically used internally by Fontkit.
* **Type**: Object

## Other Properties

### Basic properties:

<table><thead><tr><th width="155">Property</th><th>Description</th></tr></thead><tbody><tr><td><code>.type</code></td><td>The type of the font, such as 'truetype', 'cff', etc.</td></tr><tr><td><code>.defaultLanguage</code></td><td>The default language for the font, used when retrieving names and other language-specific details.</td></tr><tr><td><code>.stream</code></td><td>The readable stream from which the font is being read. Useful for reading binary data directly from the font file.</td></tr><tr><td><code>.variationCoords</code></td><td>An object representing the coordinates for variable font instances. If the font is not variable, this property is null.</td></tr><tr><td><code>._directoryPos</code></td><td>(Internal) Position of the directory within the font stream. Typically used internally by Fontkit for navigation purposes.</td></tr><tr><td><code>._tables</code></td><td>(Internal) A cache of parsed tables. Used internally by Fontkit to store tables that have been parsed.</td></tr><tr><td><code>._glyphs</code></td><td>(Internal) A cache of parsed glyphs. Used internally by Fontkit to store glyphs that have been read from the font.</td></tr><tr><td><code>.directory</code></td><td>The font's directory table, which provides an index to the rest of the tables in the font.</td></tr></tbody></table>

### Font tables as properties:

<table><thead><tr><th width="111">Property</th><th>Description</th></tr></thead><tbody><tr><td><code>.GDEF</code></td><td>Glyph Definition Table: Contains glyph class definitions, ligature caret lists, and glyph attachment positioning.</td></tr><tr><td><code>.GPOS</code></td><td>Glyph Positioning Table: Contains information about positioning glyphs in complex scripts or ligature adjustments.</td></tr><tr><td><code>.GSUB</code></td><td>Glyph Substitution Table: Defines glyph substitutions, such as ligatures, contextual alternates, etc.</td></tr><tr><td><code>.OS/2</code></td><td>OS/2 and Windows Specific Table: Contains metrics, glyph index ranges, style flags, and other font metadata.</td></tr><tr><td><code>.cmap</code></td><td>Character to Glyph Index Mapping Table: Maps character codes to glyph indices.</td></tr><tr><td><code>.cvt</code></td><td>Control Value Table: Contains values used by the fpgm table and the glyf table for hinting.</td></tr><tr><td><code>.fpgm</code></td><td>Font Program: Contains hinting instructions for the font.</td></tr><tr><td><code>.gasp</code></td><td>Grid-fitting and Scan-conversion Procedure Table: Contains information for grid-fitting and anti-aliasing.</td></tr><tr><td><code>.glyf</code></td><td>Glyph Data Table: Contains the outlines of the glyphs in the font.</td></tr><tr><td><code>.head</code></td><td>Font Header Table: Contains global font information such as bounding box, version, etc.</td></tr><tr><td><code>.hhea</code></td><td>Horizontal Header Table: Contains horizontal metrics and settings.</td></tr><tr><td><code>.hmtx</code></td><td>Horizontal Metrics Table: Contains metrics for each glyph's horizontal layout.</td></tr><tr><td><code>.loca</code></td><td>Index to Location Table: Contains offsets to each glyph in the <code>glyf</code> table.</td></tr><tr><td><code>.maxp</code></td><td>Maximum Profile Table: Contains the maximum values for various font-wide parameters.</td></tr><tr><td><code>.name</code></td><td>Naming Table: Contains names for various font attributes, including designer, copyright, etc.</td></tr><tr><td><code>.post</code></td><td>PostScript Table: Contains information used for emulating PostScript fonts.</td></tr><tr><td><code>.prep</code></td><td>Control Value Program: Contains hinting instructions executed before processing any glyph in the font.</td></tr></tbody></table>

## **Methods**:

### `font.createSubset()`:

* **Description**: Creates a `Subset` object, allowing you to create a new font containing only specified glyphs.
* **Returns**: `Subset` object for further operations.

### `font.getAvailableFeatures()`:

* **Description**: Lists the OpenType layout features available in the font.
* **Returns**: Array of available feature tags.

### `font.getFont()`:

* **Description**: If the font file contains multiple fonts, retrieves a specific one.
* **Parameters**: Index or specific criteria for font selection.
* **Returns**: `Font` object.

### `font.getGlyph()`:

* **Description**: Retrieves a glyph by its ID.
* **Parameters**: Glyph ID.
* **Returns**: Corresponding `Glyph` object.

### `font.getVariation(variation)`:

* **Description**: Returns a new Font object for the given variation.
* **Parameters**: Variation criteria or name.
* **Returns**: Variation data.

### `font.getVariation(variation)`:

* **Description:** Returns a new Font object for the given variation. This method is used to obtain a specific variation of the font based on the provided variation criteria.
* **Parameters:** `variation` (Object) - An object specifying the variation criteria. The format of this object includes key-value pairs representing the variation axes. For example, `{ "wght": 400 }` sets the weight of the font to 400.
* **Returns:** Fontkit `Font` Object - A new font object that represents the specified variation of the original font.

**Example:**

{% code fullWidth="false" %}

```javascript
let currentVariation = {
    "wght": 400
};
fkFont = fkFont.getVariation(currentVariation);
```

{% endcode %}

### `font.glyphForCodePoint(codePoint)`:

* **Description**: Returns a `Glyph` object for a given Unicode code point.
* **Parameters**: Unicode code point.
* **Returns**: Corresponding `Glyph` object.

### `font.glyphsForString(string)`:

* **Description**: Returns an array of `Glyph` objects for a given string.
* **Parameters**: A string of characters.
* **Returns**: Array of `Glyph` objects.

### `font.hasGlyphForCodePoint(codePoint)`:

* **Description**: Checks if the font has a glyph for the given Unicode code point.
* **Parameters**: Unicode code point.
* **Returns**: Boolean indicating presence of the glyph.

### `font.layout(text, features, script, language)`:

* **Description**: This is used to lay out a string of text, returning a `GlyphRun` object. The `features` parameter is optional and can be used to turn on or off OpenType features. The `script` and `language` parameters can be used to set the script and language for shaping.
* **Parameters**: A string of characters, and potentially additional layout parameters.
* **Returns**: `GlyphRun` object.

### `font.getName()`:

* **Description**: Retrieves the human-readable name for a specific name ID in the font.
* **Parameters**: Name ID.
* **Returns**: String representing the name.

### `font.setDefaultLanguage()`:

* **Description**: Sets the default language for the font, affecting layout operations.
* **Parameters**: Language tag.
* **Returns**: Void (changes are applied to the `Font` object).

### `font.stringsForGlyph()`:

* **Description**: Retrieves strings that map to a specific glyph.
* **Parameters**: Glyph ID or `Glyph` object.
* **Returns**: Array of strings.

### `font._decodeDirectory()`:

* **Description**: (Internal) Decodes the directory structure of the font, which is a key part of its binary data.
* **Parameters**: Typically involves references or offsets from the font file.
* **Returns**: Decoded directory structure.

### `font._decodeTable()`:

* **Description**: (Internal) Decodes a specific table from the font's binary data.
* **Parameters**: Table references or names from the font file.
* **Returns**: Decoded table data.

### `font._getBaseGlyph()`:

* **Description**: (Internal) Retrieves the base glyph for a particular character or code point.
* **Parameters**: Usually a character or code point.
* **Returns**: Corresponding base `Glyph` object.

### `font._getTable()`:

* **Description**: (Internal) Fetches a specific table from the font.
* **Parameters**: Table name or reference.
* **Returns**: Table data.

### `font._getTableStream()`:

* **Description**: (Internal) Retrieves a stream for reading a specific table from the font's binary data.
* **Parameters**: Table name or reference.
* **Returns**: Data stream for the specified table.

## **Layout a String and Access Glyphs**:

```javascript
const run = font.layout('Hello, Fontkit!');

// Iterate over each glyph in the GlyphRun to put together pathData
let pathData = '';
let x = 0;
let y = 0;
run.glyphs.forEach((glyph, index) => {
  console.log(`Glyph ID: ${glyph.id}, Unicode: ${String.fromCodePoint(...glyph.codePoints)}`);
  const position = run.positions[index];
  if (glyph.path) {
    pathData += glyph.path
      .scale(1, -1)
      .translate(x + position.xOffset, y + position.yOffset)
      .toSVG();
    x += position.xAdvance;
    y += position.yAdvance;
  }
});
console.log(pathData);
```


# GlyphRun Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

The `GlyphRun` object in Fontkit represents a sequence of glyphs and their associated positions. When you layout a string using the `font.layout()` method, it returns a `GlyphRun` object.

## **Properties**:

### `glyphRun.glyphs`:

* **Description**: An array of `Glyph` objects representing the individual glyphs in the run.
* **Type**: Array of `Glyph` objects

### `glyphRun.positions`:

* **Description**: An array of position objects, where each position corresponds to the `Glyph` at the same index in the `glyphs` array. Each position object typically contains `x` and `y` offsets and an advance width and height.
* **Type**: Array of Position Objects. Each position object has properties:
  * `xAdvance`: The amount to move the pen in the x-direction after drawing the glyph.
  * `yAdvance`: The amount to move the pen in the y-direction after drawing the glyph.
  * `xOffset`: The x offset to apply when drawing this glyph.
  * `yOffset`: The y offset to apply when drawing this glyph.

### `glyphRun.features`:

* **Description**: An array of OpenType feature tags applied to this run, which can affect the final set of glyphs and their positions.
* **Type**: Array of Strings

### `glyphRun.script`:

* **Description**: The script (or writing system) used for this run of text, as determined by the shaping engine.
* **Type**: String

### `glyphRun.language`:

* **Description**: The language tag for this run of text, which can affect shaping in some scripts.
* **Type**: String

### `glyphRun.direction`:

* **Description**: The text direction for this run. Common values include 'ltr' (left-to-right) and 'rtl' (right-to-left).
* **Type**: String

### `glyphRun.advanceWidth`:

* **Description**: The total advance width of the glyph run. This is the sum of the horizontal advances of all the glyphs in the run, and it represents the width that the glyph run would occupy if rendered.
* **Type**: Number

### `glyphRun.advanceHeight`:

* **Description**: The total advance height of the glyph run. This is particularly relevant for vertical text layouts.
* **Type**: Number

### `glyphRun.bbox`:

* **Description**: The bounding box of the glyph run. It encompasses all the glyphs in the run and provides `minX`, `minY`, `maxX`, and `maxY` properties.
* **Type**: Object

## **Methods**:

The main interaction with a `GlyphRun` object revolves around accessing its properties rather than calling methods. Most of the manipulation or querying one would do with the `GlyphRun` results involves working directly with the properties listed above. For instance, iterating over the glyphs or positions to perform certain tasks or calculations.


# Glyph Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

The `Glyph` object in Fontkit represents an individual glyph in the font, which corresponds to a specific visual representation of one or more characters.

## **Properties**:

### `glyph.id`:

* **Description**: A unique identifier for the glyph within its font.
* **Type**: Number

### `glyph.path`:

* **Description**: The path object for the glyph, representing the glyph's outlines and can be rendered or used for various operations.
* **Type**: `Path` object

### `glyph.name`:

* **Description**: The name of the glyph, which can be a standard glyph name or a custom one defined by the font creator.
* **Type**: String

### `glyph.type`:

* **Description**: The type of glyph, such as 'simple' or 'composite'.
* **Type**: String

### `glyph.codePoints`:

* **Description**: An array of Unicode code points that the glyph represents. This can be more than one for ligatures and other combined forms.
* **Type**: Array of Numbers

### `glyph.advanceWidth`:

* **Description**: The advance width of the glyph, representing the space the glyph occupies horizontally.
* **Type**: Number

### `glyph.advanceHeight`:

* **Description**: The advance height of the glyph, representing the vertical space the glyph occupies. Relevant for vertical text layouts.
* **Type**: Number

### `glyph.bbox`:

* **Description**: The bounding box of the glyph, encompassing the entire glyph and providing `minX`, `minY`, `maxX`, and `maxY` properties.
* **Type**: Object

### `glyph.cbox`:

* **Description**: The control bounding box of the glyph, which encompasses all control points of the glyph's path. Useful for some precise layout operations.
* **Type**: Object

### `glyph.isMark`:

* **Description**: Indicates if the glyph is a mark glyph, which is used for combining characters in many scripts.
* **Type**: Boolean

### `glyph.isLigature`:

* **Description**: Indicates if the glyph is a ligature, representing multiple characters combined into a single glyph.
* **Type**: Boolean

### `glyph.ligatureCaretPositions`:

* **Description**: An array indicating positions within the glyph where carets should be drawn when the glyph is selected. Relevant for ligatures where multiple characters combine into a single glyph.
* **Type**: Array of Numbers

### `glyph._font`:

* **Description**: (Internal) Reference to the font object the glyph belongs to.
* **Type**: `Font` object

### `glyph._metrics`:

* **Description**: (Internal) Metrics data for the glyph. Typically used internally by Fontkit.
* **Type**: Object

## **Methods**:

### `glyph._getPath()`:

* **Description**: (Internal) Retrieves the path data for the glyph, which can be used for rendering or other operations.
* **Returns**: A `Path` object representing the glyph's outlines.

### `glyph._getMetrics()`:

* **Description**: (Internal) Retrieves the metrics for the glyph, which define its layout characteristics.
* **Returns**: Metrics data.

### `glyph._getContours()`:

* **Description**: (Internal) Retrieves the contours of the glyph, which define the glyph's shape.
* **Returns**: An array of contours.

### `glyph._getCBox()`:

* **Description**: (Internal) Retrieves the control bounding box of the glyph. This box encompasses all control points of the glyph's path.
* **Returns**: Object

### `glyph._getPhantomPoints(glyph)`:

* **Description**: (Internal) Retrieves the phantom points for the glyph, which are often used for hinting and layout purposes.
* **Returns**: An array of phantom points.

### `glyph._parseGlyphCoord(stream, prev, short, same)`:

* **Description**: (Internal) Parses specific coordinates from the glyph data, often used in the decoding process.
* **Parameters**: Typically involves parameters related to font data or encoding specifics.
* **Returns**: Parsed coordinates (usually Numbers or Objects).

### `glyph._decode()`:

* **Description**: (Internal) Decodes the glyph data, which can be either simple or composite, depending on the glyph type.
* **Parameters**: Typically data or stream references from the font file.
* **Returns**: Decoded glyph data.

### `glyph._decodeSimple(glyph, stream):`

* **Description**: (Internal) Decodes the data for a simple glyph type.
* **Parameters**: Typically data or stream references from the font file.
* **Returns**: Decoded simple glyph data.

### `glyph._decodeComposite(glyph, stream, offset = 0):`

* **Description**: (Internal) Decodes the data for a composite glyph type.
* **Parameters**: Typically data or stream references from the font file.
* **Returns**: Decoded composite glyph data.

## **Render a Glyph's Path to SVG**:

```javascript
// Get a glyph for a specific code point (e.g., Unicode for "A")
const glyph = font.glyphForCodePoint(65);

// Convert the glyph's path to SVG
const svgPathData = glyph.path.toSVG();

console.log(`SVG Path Data for "A": ${svgPathData}`);
```


# Path Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

The `Path` object in Fontkit represents the outline of a glyph. You can use it to render the glyph on a canvas, SVG, or any other graphic surface.

## **Properties**:

### `path.commands`

An array of path commands. Each command is an object with a `type` property, which can be 'moveTo', 'lineTo', 'curveTo', 'qcurveTo', or 'closePath', and the corresponding x and y coordinates (or control points for curves).

### `path.bbox`

The bounding box of the path, which is the rectangle that encloses the path's outline. This object contains properties: `minX`, `minY`, `maxX`, and `maxY`.

### `path.cbox`

The control bounding box of the path, which is similar to the bounding box but includes Bezier control points.

## **Methods**:

### `path.rotate(angle)`

* **Description**: Rotates the path around the origin `(0, 0)`.
* **Parameters**:
  * `angle`: The rotation angle in radians.
* **Returns**: The modified `Path` object.
* **Example**: Rotating a path by 45 degrees (converted to radians):

  ```javascript
  path.rotate(Math.PI / 4);
  ```

### `path.scale(scaleX, scaleY = scaleX)`

* **Description**: Scales the path by a factor in the x and y directions.
* **Parameters**:
  * `scaleX`: The scaling factor in the x-direction.
  * `scaleY`: (Optional) The scaling factor in the y-direction. If not provided, it defaults to the value of `scaleX`, resulting in uniform scaling.
* **Returns**: The modified `Path` object.
* **Example**: Scaling a path by 2x in the x-direction and 0.5x in the y-direction:

  ```javascript
  path.scale(2, 0.5);
  ```

### `path.transform(m0, m1, m2, m3, m4, m5)`

* **Description**: Applies a 2x3 transformation matrix to the path. This can represent combinations of translations, rotations, scaling, and skewing.
* **Parameters**:
  * `m0`, `m1`, `m2`, `m3`, `m4`, `m5`: The elements of the 2x3 transformation matrix.
* **Returns**: The modified `Path` object.
* **Example**: Applying a transformation matrix:

  ```javascript
  path.transform(1, 0, 0, 1, 10, 20); 
  // This example translates the path by 10 units in x and 20 units in y.
  ```

### `path.translate(x, y)`

* **Description**: Translates (moves) the path by a specified amount in the x and y directions.
* **Parameters**:
  * `x`: The translation amount in the x-direction.
  * `y`: The translation amount in the y-direction.
* **Returns**: The modified `Path` object.
* **Example**: Translating a path by 10 units in x and 20 units in y:

  ```javascript
  path.translate(10, 20);
  ```

### `path.mapPoints(fn)`

* **Description**: Maps each point in the path to a new point by applying a given function. This is a general-purpose method that allows you to apply arbitrary transformations to each point in the path.
* **Parameters**:
  * `fn`: A function that takes a point as an argument (an object with `x` and `y` properties) and returns a new point (also an object with `x` and `y` properties).
* **Returns**: The modified `Path` object.
* **Example**: Mapping points to apply a custom transformation:

  ```javascript
  path.mapPoints(point => ({
    x: point.x + 10,
    y: point.y - 5
  }));
  ```

### `path.moveTo(x, y)`

Moves the "pen" to a new location without drawing anything. This sets the starting point for a new sub-path.

### `path.lineTo(x, y)`

Draws a straight line from the current position to the specified (`x`, `y`) point.

### `path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)`

Draws a cubic Bezier curve from the current position to the specified (`x`, `y`) point using (`cp1x`, `cp1y`) as the control point for the start of the curve and (`cp2x`, `cp2y`) as the control point for the end of the curve.

### `path.quadraticCurveTo(cpx, cpy, x, y)`

Draws a quadratic Bezier curve from the current position to the specified (`x`, `y`) point using (`cpx`, `cpy`) as the control point.

### `path.closePath()`

Closes the current sub-path by drawing a straight line back to its starting point. This is often used when defining closed shapes.

### `path.toSVG()`

Converts the path to an SVG path data string, which can be used to render the path using SVG.

### `path.toFunction()`

Converts the path to a JavaScript function with an API similar to the Canvas 2D context. This can be used for custom rendering.


# Subset Object

{% hint style="info" %}
This documentation for [fontkit](https://github.com/foliojs/fontkit) is created and provided by the [Typogram](https://typogram.co/) team. It’s a third-party documentation intended to delve deeper into the fontkit API. For the most accurate information, refer to [fontkit’s official documentation](https://github.com/foliojs/fontkit#readme).
{% endhint %}

Fontkit can perform font subsetting, i.e. the process of creating a new font from an existing font where only the specified glyphs are included. This is useful to reduce the size of large fonts, such

## Creating a Subset:

### `font.createSubset()`

* **Description**: Creates a new subset from the font.
* **Returns**: A new `Subset` object.

## Properties

### `subset.font`:

* **Type**: `Font`
* **Description**: The original font from which the subset is derived. It provides a reference to the main font object, allowing access to all its properties, methods, and associated data.

### `subset.glyphEncoder`:

* **Type**: Object or Encoder
* **Description**: The encoder responsible for encoding the glyphs when creating the subset. This will often handle the conversion of glyph data into the required format for the subset.

### `subset.glyphs`:

* **Type**: Array of `Glyph` objects
* **Description**: An array containing all the glyphs that are included in the subset. Each glyph is an instance of the `Glyph` object, encapsulating its individual properties, metrics, and path data.

### `subset.mapping`:

* **Type**: Object
* **Description**: Represents the mapping between the glyphs in the original font and their corresponding entries in the subset. This ensures that when text is rendered using the subset, the correct glyphs are displayed.

## Methods:

### `subset.includeGlyph(glyph)`

* **Description**: Includes the given glyph in the subset.
* **Parameters**:
  * `glyph`: A `Glyph` object or glyph ID to be included in the subset.

### `subset.encode()`

* **Description**: Encodes the subset font.
* **Returns**: A `Uint8Array` containing the encoded font data.

## Example:

```javascript
// Create a new subset
const subset = font.createSubset();

// Include glyphs for the string "Hello, World!"
for (const char of 'Hello, World!') {
  const glyph = font.glyphForCodePoint(char.codePointAt(0));
  subset.includeGlyph(glyph);
}

// Encode the subset into a Uint8Array
const subsetData = subset.encode();

// The resulting subsetData can be used for embedding in a PDF or other purposes.
```


