2017年8月31日星期四

How to extract SVG data from TTF and OTF with Java and C/C++

Most people already knew that TTF and OTF are the most popular font formats we are using nowadays in our computers. A number of creative font designers work on all kinds of beautiful fonts to help us to present our mind on screens or papers. When you get a font file, every word has its own space inside to store some information about how to draw the word. In effect, TTF and OTF normally store vector graphics to represent the words. If a font file only include 26 English letters, the size of the font file would be pretty small(about 100KB or less); But for a Chinese font file, the size of the file could be much bigger(larger than 10MB) as there are more than 30 thousands Chinese words available to use.

Considering all those vector graphics available in a font file, we should be able to extract word glyph outlines and translate them into SVG format. Do we need to read TTF or OTF specification before we start extracting? Not really, there are some utilities and libraries can help us to achieve this goal.

LibraryLanguageDescription
Apache™ BatikJavaBatik is a SVG toolkit which include a utility called ttf2svg: lets you convert a range of characters from a TrueType Font into the SVG font format.
FreeType ProjectC/C++FreeType is a freely available software library to render fonts. 

ttf2svg example can be found here: https://xmlgraphics.apache.org/batik/tools/font-converter.html

FreeType supplies a example to extract vector glyph and translate into SVG: https://www.freetype.org/freetype2/docs/tutorial/example5.cpp

The example from FreeType is too simple and available for one English letter. But it can be easily modified to achieve other purpose, such as handling Chinese words and reading from text file and writing vector information into JSON or SVG file. You can find this modified version here: font2svg.cpp. This program need a word.txt as input and gonna generate a word.json and a word.svg at the same directory after running. You can has any words you want to extract in word.txt and make sure words are available in the TTF or OTF file you supplied to the program.

g++ -o font2svg.exe font2svg.cpp -I/usr/include/freetype2 -I/usr/include -L/lib -lfreetype.dll -lz


If you are working in Windows environment, Cygwin can help you to compile and link the example. Just remember to install Devel at least.

Please remember, some fonts come from open source projects and some fonts have their own copyrights or licence requirements. Make sure you are using libraries to treat them in a correct and respectful way.

没有评论:

发表评论