7 UsingCustomFonts
Richard Fairhurst edited this page 2018-06-11 17:15:49 +01:00

Using Custom Fonts with Mapnik

Doing this requires three steps:

1) Place custom fonts in Mapnik's font folder or register them in different location

Python

Find the location of Mapnik's special font folder and place new fonts in it:

    $ python -c "import mapnik;print mapnik.fontscollectionpath"

Or register a custom location:

    import mapnik
    custom_fonts_dir = '/Library/Fonts/'
    mapnik.register_fonts(custom_fonts_dir)

XML

We are planning to add registration support within XML in #168

  • Also, the Nik2Img allows you to pass the --fonts argument to register custom fonts when reading and XML

C++

    mapnik::freetype_engine::register_font(std::string const& file_name)

...where file_name is the full path to the directory where the font is located (e.g., "/home/user/mapnik/fonts/unifont-Medium.ttf"). The c++ demo (source:trunk/demo/c++/rundemo) also provides an good example of how to add additional fonts.

NodeJS

var mapnik = require('mapnik');
mapnik.register_default_fonts();
mapnik.fonts().forEach( function(e) { console.log(e); });

The NodeJS interpreter might add an extra line in interactive mode. To avoid this, do

nodejs -e "var mapnik = require('mapnik');mapnik.register_default_fonts();mapnik.fonts().forEach( function(e) { console.log(e); });"

2) Figure out the exact 'face_name'

  • Ask Mapnik to print all registered face names (note: this only will show fonts already auto-registered in the fontscollectionpath):
    python -c "from mapnik import FontEngine as e;print '\n'.join(e.face_names())"
    DejaVu Sans Bold
    DejaVu Sans Bold Oblique
    DejaVu Sans Book
    DejaVu Sans Condensed
    DejaVu Sans Condensed Bold
    [..snip..]
  • Or, register custom fonts and then show their face names:
    from mapnik import register_fonts, FontEngine
    custom_fonts_dir = '/Library/Fonts/'
    register_fonts(custom_fonts_dir)
    for face in FontEngine.face_names(): print face
    ... 
    Al Bayan Bold
    Al Bayan Plain
    Andale Mono Regular
    Arial Black Regular
    [...snip...]

3) Pass the 'face_name' to the TextSymbolizer or ShieldSymbolizer

    <TextSymbolizer name="FIELD_NAME" face_name="DejaVu Sans Condensed Bold" size="10" fill="black" />

Further references