svgicons2svgfont

repository·main·Indexed 18 days ago

https://github.com/nfroidure/svgicons2svgfont

A tool for merging multiple SVG icons into a single SVG font. It converts SVG shapes into paths and supports ligatures and unicode mapping. It provides a CLI for directory-to-font conversion and a Node.js API via the SVGIcons2SVGFontStream and SVGIconsDirStream classes for integration into custom workflows and build systems like Gulp, Grunt, and Stylus.

Tokens
4.8K
Snippets
9
Records
15
Agent score
62%

What's inside svgicons2svgfont

  1. Integrate svgicons2svgfont with build systems

    main

    The following plugins and tools are available for integrating svgicons2svgfont into various build environments:

    Grunt

    • grunt-svgicons2svgfont
    • grunt-webfont

    Gulp

    • gulp-iconfont
    • gulp-svgicons2svgfont

    Stylus

    • stylus-iconfont

    Mimosa

    • mimosa-svgs-to-iconfonts
  2. Use SVGIcons2SVGFontStream in Node.js scripts

    main

    You can integrate svgicons2svgfont into your Node.js workflows using the SVGIcons2SVGFontStream class. This class is a stream that accepts SVG files as input and outputs an SVG font.

    To use it:

    1. Instantiate SVGIcons2SVGFontStream with your desired configuration.
    2. Pipe the stream to a write stream to save the resulting font.
    3. Create read streams for each icon file.
    4. Attach a metadata object to each icon read stream containing the unicode (array of strings) and name (string).
    5. Write the icon streams to the font stream.
    6. Call .end() on the font stream when finished.
    import { SVGIcons2SVGFontStream } from 'svgicons2svgfont';
    import { createReadStream, createWriteStream } from 'node:fs';
    
    const fontStream = new SVGIcons2SVGFontStream({
      fontName: 'hello',
    });
    
    // Setting the font destination
    fontStream
      .pipe(createWriteStream('fonts/hello.svg'))
      .on('finish', function () {
        console.log('Font successfully created!');
      })
      .on('error', function (err) {
        console.log(err);
      });
    
    // Writing glyphs
    const glyph1 = createReadStream('icons/icon1.svg');
    glyph1.metadata = {
      unicode: ['\uE001\uE002'],
      name: 'icon1',
    };
    fontStream.write(glyph1);
    
    // Do not forget to end the stream
    fontStream.end();
  3. How SVGIcons2SVGFontStream processes icons

    main

    The stream operates in three main phases:

    1. Parsing (_transform): As SVGIconStream objects arrive, the stream uses a SAX parser to traverse the SVG elements. It handles transform attributes by maintaining a transformation stack, and converts various SVG shapes (rect, line, polyline, polygon, circle, ellipse, path) into SVGPathData.
    2. Bounds Calculation (_flush): Once all icons are parsed, the stream calculates the maximum glyph height and width. If usePathBounds is enabled, it uses the actual bounding box of the paths to determine dimensions.
    3. Font Generation (_flush): The stream calculates the final fontWidth, ascent, and descent. It then iterates through all glyphs, applies scaling (including normalize logic), applies vertical symmetry (flipping the Y axis for font coordinates), and centers the paths if requested. Finally, it writes the XML structure for the SVG font.
  4. Configure SVGIcons2SVGFontStream options

    main

    When instantiating new SVGIcons2SVGFontStream(options), you can provide the following configuration:

    • fontName (String, default: 'iconfont'): The font family name.
    • fontId (String, default: fontName): The font id.
    • fontStyle (String, default: ''): The font style.
    • fontWeight (String, default: ''): The font weight.
    • fixedWidth (Boolean, default: false): Creates a monospace font based on the largest icon.
    • centerHorizontally (Boolean, default: false): Centers glyphs horizontally.
    • centerVertically (Boolean, default: false): Centers glyphs vertically.
    • normalize (Boolean, default: false): Scales icons to the height of the highest icon.
    • preserveAspectRatio (Boolean, default: false): Used with normalize to scale down glyphs if width > height.
    • fontHeight (Number, default: MAX(icons.height)): The output font height.
    • round (Number, default: 10e12): SVG path rounding.
    • descent (Number, default: 0): The font descent (must be a positive value).
    • ascent (Number, default: fontHeight - descent): The font ascent.
    • metadata (String, default: undefined): Character data for the font metadata (e.g., copyright).
    • metadataProvider (Function): A function (file: string, cb: (err: any, metadata: {file: string, name: string, unicode: string[], renamed: boolean}) => void) to determine icon metadata asynchronously.
    • log (Function, default: console.log): Custom logging function. Set to function(){} to disable.
  5. Configure SVGIcons2SVGFontStreamOptions

    main

    The SVGIcons2SVGFontStream constructor accepts a partial configuration object to control how the SVG font is generated.

    Key options include:

    • fontName: The name of the font family.
    • fontId: The ID for the <font> element.
    • fixedWidth: If true, all glyphs will have the same horiz-adv-x (the calculated fontWidth).
    • descent: The descent value for the font.
    • ascent: The ascent value (defaults to fontHeight - descent if not provided).
    • round: The rounding precision for path data (defaults to 10e12).
    • metadata: A string to be placed inside a <metadata> tag in the output SVG.
    • usePathBounds: If true, glyph width and height are calculated based on the actual path bounds rather than the SVG viewBox or attributes.
    • normalize: If true, scales glyphs so they all fit within the fontHeight while preserving aspect ratio.
    • preserveAspectRatio: Used with normalize to determine scaling logic.
    • centerHorizontally / centerVertically: If true, centers the glyph paths within their allocated space.
    • fontHeight: The total height of the font (recommended to be $\ge 1000$).
    • callback: A function called after the stream is flushed, receiving the array of Glyph objects.
  6. Configure the Metadata Service options

    main

    When using getMetadataService, you can provide an options object to control how Unicode codepoints are assigned and how files are renamed.

    • prependUnicode: If true, the service will rename the source SVG file to include its assigned Unicode codepoint in the filename (e.g., uE001-icon.svg).
    • startUnicode: The starting Unicode codepoint for auto-assigning icons. The default is 0xea01 if not specified.
    // Example options
    const options = {
      prependUnicode: true,
      startUnicode: 0xf000
    };
  7. Reference: CLI options for svgicons2svgfont

    main

    List of available command-line flags for svgicons2svgfont:

    FlagLong FlagDescription
    -V--versionOutput the version number
    -v--verboseTell me everything!
    -o--output [value]File to write output to (defaults to /dev/stdout)
    -f--fontName [value]The font family name you want [default: iconfont]
    -i--fontId [value]The font id you want [default: fontName]
    -st--style [value]The font style you want
    -we--weight [value]The font weight you want
    -w--fixedWidthCreates a monospace font of the width of the largest input icon
    -c--centerHorizontallyCalculate the bounds of a glyph and center it horizontally
    -y--centerVerticallyCenters the glyphs vertically in the generated font
    -n--normalizeNormalize icons by scaling them to the height of the highest icon
    -p--preserveAspectRatioUsed with normalize to scale down glyph if the SVG width is greater than the height
    -h--height [value]The output font height [MAX(icons.height)]
    -r--round [value]Setup the SVG path rounding [default: 10e12]
    -d--descent [value]The font descent [default: 0]
    -a--ascent [value]The font ascent [default: height - descent]
    -s--startUnicode [value]The start unicode code point for unprefixed files [default: 0xEA01]
    -u--prependUnicodePrefix files with their automatically allocated unicode code point
    --help--helpDisplay help for command
    Usage: svgicons2svgfont [options] <icons ...>
    
    Options:
      -V, --version               output the version number
      -v, --verbose               tell me everything!
      -o, --output [/dev/stdout]  file to write output to
      -f, --fontName [value]      the font family name you want [iconfont]
      -i, --fontId [value]        the font id you want [fontName]
      -st, --style [value]        the font style you want
      -we, --weight [value]       the font weight you want
      -w, --fixedWidth            creates a monospace font of the width of the largest input icon
      -c, --centerHorizontally    calculate the bounds of a glyph and center it horizontally
      -y, --centerVertically      centers the glyphs vertically in the generated font.
      -n, --normalize             normalize icons by scaling them to the height of the highest icon
      -p, --preserveAspectRatio   used with normalize to scale down glyph if the SVG width is greater than the height
      -h, --height [value]        the output font height [MAX(icons.height)] (icons will be scaled so the highest has
                                  this height)
      -r, --round [value]         setup the SVG path rounding [10e12]
      -d, --descent [value]       the font descent [0]
      -a, --ascent [value]        the font ascent [height - descent]
      -s, --startUnicode [value]  the start unicode code point for unprefixed files [0xEA01]
      -u, --prependUnicode        prefix files with their automatically allocated unicode code point
      -m, --metadata              content of the metadata tag
      --help                      display help for command
  8. Reference the svgicons2svgfont CLI options

    main

    The following options are available for the svgicons2svgfont command-line interface:

    FlagDescription
    -v, --verboseTell me everything!
    -o, --output [value]File to write output to (defaults to /dev/stdout)
    -f, --fontName [value]The font family name you want (default: iconfont)
    -i, --fontId [value]The font id you want (default: fontName)
    -t, --style [value]The font style you want
    -e, --weight [value]The font weight you want
    -w, --fixedWidthCreates a monospace font of the width of the largest input icon
    -c, --centerHorizontallyCalculate the bounds of a glyph and center it horizontally
    -y, --centerVerticallyCenters the glyphs vertically in the generated font
    -n, --normalizeNormalize icons by scaling them to the height of the highest icon
    -p, --preserveAspectRatioUsed with normalize to scale down glyph if the SVG width is greater than the height
    -h, --height [value]The output font height (default: MAX(icons.height))
    -r, --round [value]Setup the SVG path rounding (default: 10e12)
    -d, --descent [value]The font descent (default: 0)
    -a, --ascent [value]The font ascent (default: height - descent)
    -s, --startUnicode [value]The start unicode code point for unprefixed files (default: 0xEA01)
    -u, --prependUnicodePrefix files with their automatically allocated unicode code point
    -m, --metadata [value]Content of the metadata tag
  9. Use the svgicons2svgfont CLI

    main

    The CLI allows you to convert a directory of SVG icons into an SVG font via the command line.

    Naming Convention for CLI: Since you cannot pass icon names or unicodes via CLI options, you must name your files using the following pattern: ${icon.unicode}-${icon.name}.svg

    Example: uEA01,uE001,uE001uE002-myicon.svg (where the last part is a ligature).

    Basic Command:

    svgicons2svgfont --fontName=hello -o font/destination/file.svg icons/directory/*.svg
    svgicons2svgfont --fontName=hello -o font/destination/file.svg icons/directory/*.svg
  10. Use the SVGIcons2SVGFontStream class

    main

    SVGIcons2SVGFontStream is a Node.js Transform stream that converts a stream of SVG icons into an SVG font format. It processes SVGIconStream objects, parses their SVG content, and outputs a single SVG file containing <font> and <glyph> definitions.

    To use it, instantiate the class with SVGIcons2SVGFontStreamOptions and pipe an SVGIconStream into it. You can provide a callback in the options to receive the processed Glyph[] array once the stream is flushed.

    import { SVGIcons2SVGFontStream } from 'svgicons2svgfont';
    
    const fontStream = new SVGIcons2SVGFontStream({
      fontName: 'my-icon-font',
      fontId: 'my-icon-font',
      descent: 200,
      callback: (glyphs) => {
        console.log('Generated glyphs:', glyphs);
      }
    });
    
    // iconStream is an instance of SVGIconStream
    iconStream.pipe(fontStream).pipe(process.stdout);
  11. Use getMetadataService to process SVG files

    main

    The getMetadataService function returns a callback-based function used to extract or assign metadata to SVG files.

    Filename Pattern for Manual Unicode Assignment: To manually assign a Unicode codepoint, name your file using the pattern u<hex>-<name>.svg (e.g., uE001-home.svg). The service will parse the uE001 part and use it as the glyph's Unicode.

    Automatic Assignment: If no Unicode pattern is detected in the filename, the service will automatically assign the next available codepoint starting from startUnicode.

    import { getMetadataService } from 'svgicons2svgfont/src/metadata';
    
    const service = getMetadataService({ prependUnicode: true, startUnicode: 0xea01 });
    
    service('path/to/icon.svg', (error, metadata) => {
      if (error) {
        console.error('Error processing metadata:', error);
        return;
      }
      console.log('Metadata:', metadata);
    });