fontkit

repository·master·Indexed 23 days ago

https://github.com/foliojs/fontkit

An advanced font engine for Node and the browser (version 2.0.4) that supports TTF, WOFF, WOFF2, TrueType Collections, and DFont. It provides features for OpenType shaping, glyph path extraction, font subsetting, and AAT variation font control. The library includes APIs for text layout via font.layout(), metadata and metrics access, color glyph support (SBIX and COLR), and tools for converting Unicode scripts to OpenType tags.

Tokens
2K
Snippets
2
Records
18
Agent score
82%

What's inside fontkit

  1. Create font subsets for PDF embedding

    master

    Fontkit supports subsetting, which creates a new font containing only specified glyphs. This is primarily used to reduce font size for PDF generation.

    Note: Currently, subsets are designed for PDF embedding and may not work as standalone files because they lack essential tables like cmap.

    To use subsets:

    1. Call font.createSubset() to create a Subset object.
    2. Use subset.includeGlyph(glyph) to add specific glyph objects or glyph IDs to the subset.
    3. Call subset.encode() to get the resulting font as a Uint8Array.
  2. Initialize fontkit with supported formats

    master
    The fontkit entrypoint automatically registers support for several font formats including TTF, WOFF, WOFF2, TrueType Collections, and DFont. This allows the library to handle these formats when using the primary loading methods.
  3. Access glyph properties and paths

    master

    Glyph objects (returned by font.layout or font.getGlyph) represent individual visual characters. They include:

    • id: The glyph ID.
    • name: The glyph name.
    • codePoints: An array of Unicode code points represented by this glyph (useful for ligatures).
    • path: A vector Path object representing the glyph.
    • bbox: The tight bounding box of the glyph outline.
    • cbox: The control box (faster to compute than bbox, but less accurate).
    • advanceWidth: The glyph's advance width.

    Rendering:

    • glyph.render(ctx, size): Renders the glyph to a provided graphics context at a specific size.
    • glyph.path.toSVG(): Converts the glyph vector path to an SVG path string.
  4. Open font files with fontkit.open, openSync, or create

    master

    Fontkit provides three primary ways to load font data. For collection fonts (like .ttc or .dfont), you can provide an optional postscriptName to extract a specific font from the collection instead of receiving a collection object.

    • fontkit.open(filename, postscriptName = null): Opens a font file asynchronously and returns a Promise that resolves to a font object.
    • fontkit.openSync(filename, postscriptName = null): Opens a font file synchronously and returns a font object.
    • fontkit.create(buffer, postscriptName = null): Returns a font object for the provided buffer.
  5. Create a font subset with font.createSubset()

    master

    You can create a new, smaller font file containing only the specific glyphs you need using the subsetting API. This is useful for reducing file size in web environments.

    1. Call font.createSubset() to get a Subset object.
    2. Use subset.includeGlyph(glyph) for each glyph you want to keep.
    3. Call subset.encode() to get the encoded buffer.
    var subset = font.createSubset();
    run.glyphs.forEach(function(glyph) {
      subset.includeGlyph(glyph);
    });
    
    let buffer = subset.encode();
  6. Use the Subset API

    master

    The Subset object provides methods to include specific glyphs and encode the resulting font data.

    • subset.includeGlyph(glyph): Includes the given glyph object or glyph ID in the subset.
    • subset.encode(): Returns a Uint8Array containing the encoded font file.
  7. Work with variation fonts

    master

    Fontkit supports AAT variation fonts, allowing control over axes like weight, width, and slant.

    • font.variationAxes: Returns an object describing available axes (keys are 4-letter tags; values include name, min, default, and max).
    • font.namedVariations: Returns an object of designer-specified named variations (e.g., 'Bold').
    • font.getVariation(variation): Returns a new font object for a specific variation. The variation parameter can be a settings object (e.g., { 'wght': 700 }) or a string name.
  8. Perform text layout and shaping with font.layout()

    master

    To correctly render text with advanced features like ligatures, kerning, and OpenType/AAT substitutions, use font.layout(string, features). This method returns a GlyphRun object containing an array of Glyphs and GlyphPositions.

    • string: The text to layout.
    • features: An array of OpenType feature tags (e.g., ['kern', 'liga']) or an object mapping feature tags to booleans (e.g., { kern: true, liga: false }).

    GlyphPosition objects include xAdvance, yAdvance, xOffset, and yOffset.

  9. Handle color glyphs (Emoji)

    master

    Fontkit supports color emoji formats including Apple's SBIX (bitmap) and Microsoft's COLR (vector).

    • For SBIX (Bitmap): Use glyph.getImageForSize(size) to retrieve an object containing image data (usually PNG) and metadata.
    • For COLR (Vector): Use glyph.layers to access an array of objects representing the glyph's color layers in render order.
  10. Extract fonts from a Font Collection

    master

    When opening collection files (like .ttc), fontkit may return a collection object. You can access individual fonts within it:

    • collection.fonts: A lazily-loaded array of all fonts in the collection.
    • collection.getFont(postscriptName): Retrieves a specific font from the collection using its PostScript name.
  11. Manipulate and render Path objects

    master

    Path objects are returned by glyphs and represent the actual vector outlines. You can use them to build paths manually or convert existing glyph outlines into SVG data or render functions.

    Path Construction Methods

    • path.moveTo(x, y): Moves the virtual pen to the given x, y coordinates.
    • path.lineTo(x, y): Adds a line from the current point to x, y.
    • path.quadraticCurveTo(cpx, cpy, x, y): Adds a quadratic curve using cpx, cpy as the control point.
    • path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y): Adds a cubic bezier curve using cp1x, cp1y and cp2x, cp2y as control points.
    • path.closePath(): Closes the current sub-path by drawing a straight line back to the starting point.

    Path Output and Conversion

    • path.toFunction(): Compiles the path into a JavaScript function that can be applied to a graphics context for rendering.
    • path.toSVG(): Converts the path into an SVG path data string.

    Path Geometry Properties

    • path.bbox: The exact bounding box (the smallest rectangle containing the entire shape, including control points).
    • path.cbox: The control box. Includes all points (including control points) and is faster to compute than bbox, but may be less accurate if control points lie outside the visible shape.