Getting a List of Installed Fonts with Flash and Javascript

Posted on July 13, 2010
Filed under ActionScript 3, Flex, Miscallaneous, Programming

When implementing the feature in the icalBuddy examples page where the font used for the output examples could be changed interactively I needed to get a list of all the fonts installed on the current user’s computer. This blog post from 2006 explains how to do it, but it refers to the deprecated ActionScript 2 API so I had to figure out how to do it with AS3.

Demo

Here’s a small demo where you can see the feature at work: Font List Example. The sources shown below are used in this demo.

Implementation

We need a small Flash app and some Javascript. Below is the source code for the Flash app.

Note that you don’t need the Flash authoring app from Adobe in order to compile this; you can simply use the mxmlc compiler in the Flex SDK (which is open source).

// FontList.as
package {
   
    import flash.display.Sprite;
    import flash.text.Font;
    import flash.text.FontType;
    import flash.text.FontStyle;
    import flash.external.ExternalInterface;
   
    public class FontList extends Sprite
    {
        public function FontList()
        {
            ExternalInterface.call('populateFontList', getDeviceFonts());
        }
       
        public function getDeviceFonts():Array
        {
            var embeddedAndDeviceFonts:Array = Font.enumerateFonts(true);
           
            var deviceFontNames:Array = [];
            for each (var font:Font in embeddedAndDeviceFonts)
            {
                if (font.fontType == FontType.EMBEDDED
                    || font.fontStyle != FontStyle.REGULAR
                    )
                    continue;
                deviceFontNames.push(font.fontName);
            }
           
            deviceFontNames.sort();
            return deviceFontNames;
        }
    }
}

Notice how the Flash app calls a Javascript function populateFontList() via the ExternalInterface. Now we just need to implement that function in the page where we embed the Flash object:

function populateFontList(fontArr)
{
    for (var key in fontArr)
    {
        var fontName = fontArr[key];
       
        // trim
        fontName = fontName.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
       
        if (fontName.match(/[_\-\s]Italic$/)
            || fontName.match(/[_\-\s](Demi)?[Bb]old$/)
            || fontName.match(/[_\-\s]Medium$/)
            || fontName.match(/[_\-\s](Ultra)?[Ll]ight$/)
            || fontName.match(/[_\-\s]Condensed$/)
            )
            // font is "non-regular" (i.e. bold, italic etc.)
            // (do something here with fontName)
        else
            // font is "regular"
            // (do something here with fontName)
    }
}

Comments

12 Responses to “Getting a List of Installed Fonts with Flash and Javascript”

Show/hide comments & reply form: