Part I · Getting started
3. Quick start: shaping text, then drawing it
The previous chapter ran HarfBuzz’s tools: hb-shape to see what shaping does to a line of text, and hb-vector and hb-raster to draw it. This chapter shows how to write programs that do the same, small versions of those three tools, in four languages:
- C, with HarfBuzz itself;
- JavaScript, with harfbuzzjs, HarfBuzz compiled to WebAssembly;
- Python, with uharfbuzz, HarfBuzz’s Python bindings;
- Rust, with HarfRust, a port of HarfBuzz’s shaping to Rust.
Each language’s section starts with the smallest useful HarfBuzz program: it loads a font, shapes a string, and prints the glyphs that come out, as hb-shape does. Two more programs then draw those glyphs where shaping put them, as SVG and as a PNG. The rest of the book explains what happens at each step; here the steps are just run.
This chapter is not only for programmers who want HarfBuzz in their own software. It’s also for font engineers who script their work: the Python section is the place to start for tests and proofs that shape text in bulk. Its first program is worth trying even for a reader who has never written one. It is 25 lines, it needs one
pip install, and changing it to shape a whole word list with your own font is a small step. Type designers who only want to see what HarfBuzz does with a font have what they need in the previous chapter’s tools, and can skip ahead. How to read this book says which other chapters a programmer needs.This book explains what HarfBuzz does inside; it isn’t HarfBuzz’s manual. HarfBuzz’s own documentation, its user manual and API reference, is the definitive account of what each function does and promises, and the place to look things up while programming. The end of this chapter lists the references for the other languages too.
Every program below is in the book’s repository, in examples/quick-start/, and is compiled and run when the book is built: what is shown under a listing is that program’s output. The commands around them are hand-written.
All of the examples use Libre Baskerville, a Baskerville by Impallari Type under the SIL Open Font License, and the text “office coffee”, as the previous chapter did. The text is chosen so that shaping shows: the font’s standard ligatures turn the ffi of “office” and the ff of “coffee” into one glyph each, so the 13 characters become ten glyphs. The font is in the book’s repository, in fonts/quick-start/, and comes from Google Fonts, which is where to get it:
curl -L -o LibreBaskerville.ttf \
"https://github.com/google/fonts/raw/main/ofl/librebaskerville/LibreBaskerville%5Bwght%5D.ttf"
It is a variable font, with weights from 400 to 700, and every program here draws its default, 400.
HarfBuzz in C
The first C program uses HarfBuzz itself, libharfbuzz. The two that draw also use HarfBuzz’s drawing libraries: libharfbuzz-vector for SVG and libharfbuzz-raster for pixels, the ones the two tools are built on.
Glyphs, as hb-shape prints them
examples/quick-start/c/text-to-glyphs.c/* Shape a line of text and print the glyphs, as hb-shape does.
* usage: text-to-glyphs FONT TEXT */
#include <stdio.h>
#include <hb.h>
int main (int argc, char **argv)
{
if (argc != 3) { fprintf (stderr, "usage: %s FONT TEXT\n", argv[0]); return 1; }
/* Load the font: file → blob → face → font. */
hb_blob_t *blob = hb_blob_create_from_file_or_fail (argv[1]);
if (!blob) { fprintf (stderr, "can't read %s\n", argv[1]); return 1; }
hb_face_t *face = hb_face_create (blob, 0);
hb_font_t *font = hb_font_create (face);
/* Shape: characters in, positioned glyphs out. */
hb_buffer_t *buf = hb_buffer_create ();
hb_buffer_add_utf8 (buf, argv[2], -1, 0, -1);
hb_buffer_guess_segment_properties (buf); /* script, language, direction */
hb_shape (font, buf, NULL, 0);
unsigned count;
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buf, &count);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (buf, &count);
/* Print each glyph: name=cluster, @offset if it has one, +advance. */
printf ("[");
for (unsigned i = 0; i < count; i++)
{
char name[64];
hb_font_glyph_to_string (font, info[i].codepoint, name, sizeof name);
printf ("%s%s=%u", i ? "|" : "", name, info[i].cluster);
if (pos[i].x_offset || pos[i].y_offset)
printf ("@%d,%d", pos[i].x_offset, pos[i].y_offset);
printf ("+%d", pos[i].x_advance);
}
printf ("]\n");
hb_buffer_destroy (buf);
hb_font_destroy (font);
hb_face_destroy (face);
hb_blob_destroy (blob);
return 0;
}
[o=0+654|f_f_i=1+973|c=4+536|e=5+573|space=6+287|c=7+536|o=8+654|f_f=9+718|e=11+573|e=12+573]hb-shape --utf8-clusters printsThe program does three things, and every HarfBuzz program does them.
Load the font. A blob holds the file’s bytes, a face reads the font in it, and a font is the face at a size. Nothing here sets a size, so the font works in font units, and so does everything after it.
Shape. The text goes into a buffer as UTF-8. hb_buffer_guess_segment_properties works out the script, language, and direction from the text and the locale. A real application should set them, as Why shaping exists explains. hb_shape turns the characters into glyphs: after it, each hb_glyph_info_t’s codepoint is a glyph ID, not a character.
Read the result. After shaping, the buffer holds two arrays of the same length. Each hb_glyph_info_t has the glyph’s ID and its cluster, which says where in the text the glyph came from. Each hb_glyph_position_t has the glyph’s advance and its offset. The loop prints them in hb-shape’s format, which Reading this book explains: the glyph’s name, = and its cluster, @ and its offset if it has one, + and its advance. hb_font_glyph_to_string gives the glyph’s name, or gid and its number in a font without names. The ffi of “office” has become one glyph, f_f_i, and the next glyph’s cluster jumps from 1 to 4, because three characters went into it.
Programmers often want glyph IDs, not names, and hb-shape prints them with --no-glyph-names:
| Font | Text | Options | hb-shape output |
|---|---|---|---|
| LibreBaskerville.ttf | office␣coffeeU+006F U+0066 U+0066 U+0069 U+0063 U+0065 U+0020 U+0063 U+006F U+0066 U+0066 U+0065 U+0065 | --no-glyph-names | [481=0+654| |
The program can do the same by printing info[i].codepoint in place of the name: after shaping, that field holds the glyph ID. The same one-word change works in the other three languages.
The build checks that this output is exactly what hb-shape prints for the same font and text. hb-shape does it without a loop: hb_buffer_serialize writes a buffer in this format (util/shape-format.hh).
The clusters count bytes of UTF-8, because that is how the text was given to the buffer. hb-shape counts characters unless it is run with --utf8-clusters, so for text beyond ASCII the two differ until that option is added. For “office coffee” they agree.
Building and running
The programs are written for HarfBuzz 15.2.0. First, ask pkg-config which HarfBuzz you have:
pkg-config --modversion harfbuzz
If it prints 15.2.0 or later, compile and run against it:
cc text-to-glyphs.c $(pkg-config --cflags --libs harfbuzz) -o text-to-glyphs
./text-to-glyphs LibreBaskerville.ttf "office coffee"
If it prints an older version, or says the package wasn’t found, build HarfBuzz 15.2.0 yourself. It takes a minute or two, and doesn’t touch any HarfBuzz you have installed. You need a C++ compiler, pkg-config, Meson, and Ninja (brew install meson ninja pkg-config on a Mac, apt install meson ninja-build pkg-config on Debian and Ubuntu), and for the PNG program below, libpng (brew install libpng, or apt install libpng-dev). Then, in the folder with the programs:
git clone --depth 1 --branch 15.2.0 https://github.com/harfbuzz/harfbuzz.git
meson setup harfbuzz/build harfbuzz
ninja -C harfbuzz/build
Point pkg-config at the build’s meson-uninstalled folder (Building HarfBuzz), and tell the program where the libraries are:
export PKG_CONFIG_PATH=$PWD/harfbuzz/build/meson-uninstalled
cc text-to-glyphs.c $(pkg-config --cflags --libs harfbuzz) \
-Wl,-rpath,$PWD/harfbuzz/build/src -o text-to-glyphs
./text-to-glyphs LibreBaskerville.ttf "office coffee"
Building HarfBuzz explains the build in full, including Windows.
SVG with hb-vector
The SVG program is the same program with drawing in place of printing:
examples/quick-start/c/text-to-svg.c/* Shape a line of text and draw it as SVG.
* usage: text-to-svg FONT TEXT > out.svg */
#include <stdio.h>
#include <hb.h>
#include <hb-vector.h>
int main (int argc, char **argv)
{
if (argc != 3) { fprintf (stderr, "usage: %s FONT TEXT\n", argv[0]); return 1; }
/* Load the font: file → blob → face → font. */
hb_blob_t *blob = hb_blob_create_from_file_or_fail (argv[1]);
if (!blob) { fprintf (stderr, "can't read %s\n", argv[1]); return 1; }
hb_face_t *face = hb_face_create (blob, 0);
hb_font_t *font = hb_font_create (face);
/* Shape: characters in, positioned glyphs out. */
hb_buffer_t *buf = hb_buffer_create ();
hb_buffer_add_utf8 (buf, argv[2], -1, 0, -1);
hb_buffer_guess_segment_properties (buf); /* script, language, direction */
hb_shape (font, buf, NULL, 0);
unsigned count;
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buf, &count);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (buf, &count);
/* Draw each glyph at its pen position. */
hb_vector_draw_t *draw = hb_vector_draw_create_or_fail (HB_VECTOR_FORMAT_SVG);
float x = 0, y = 0;
for (unsigned i = 0; i < count; i++)
{
hb_vector_draw_set_transform (draw, 1, 0, 0, 1,
x + pos[i].x_offset, y + pos[i].y_offset);
hb_vector_draw_glyph (draw, font, info[i].codepoint,
HB_VECTOR_EXTENTS_MODE_EXPAND); /* grow the viewBox */
x += pos[i].x_advance;
y += pos[i].y_advance;
}
/* Write the SVG. */
hb_blob_t *svg = hb_vector_draw_render (draw);
unsigned length;
const char *data = hb_blob_get_data (svg, &length);
fwrite (data, 1, length, stdout);
hb_blob_destroy (svg);
hb_vector_draw_destroy (draw);
hb_buffer_destroy (buf);
hb_font_destroy (font);
hb_face_destroy (face);
hb_blob_destroy (blob);
return 0;
}
Place the glyphs. Each glyph has an advance, which moves the pen, and an offset, which moves the glyph from the pen without moving the pen. The loop adds them up. That is all the layout a single line needs: the glyphs are already in visual order, so the same loop serves right-to-left text.
Draw. hb_vector_draw_glyph draws a glyph’s outline at the current transform, and HB_VECTOR_EXTENTS_MODE_EXPAND grows the SVG’s box to fit it. hb_vector_draw_render returns the document.
It builds as the first program did, with harfbuzz-vector, HarfBuzz’s SVG library, in place of harfbuzz (and the same -Wl,-rpath option, if you built HarfBuzz yourself):
cc text-to-svg.c $(pkg-config --cflags --libs harfbuzz-vector) -o text-to-svg
./text-to-svg LibreBaskerville.ttf "office coffee" > office.svg
PNG with hb-raster
The PNG version is the same program with a size and a different drawing context:
examples/quick-start/c/text-to-png.c/* Shape a line of text and draw it as a PNG.
* usage: text-to-png FONT TEXT PIXELS > out.png */
#include <stdio.h>
#include <stdlib.h>
#include <hb.h>
#include <hb-raster.h>
int main (int argc, char **argv)
{
if (argc != 4) { fprintf (stderr, "usage: %s FONT TEXT PIXELS\n", argv[0]); return 1; }
hb_blob_t *blob = hb_blob_create_from_file_or_fail (argv[1]);
if (!blob) { fprintf (stderr, "can't read %s\n", argv[1]); return 1; }
hb_face_t *face = hb_face_create (blob, 0);
hb_font_t *font = hb_font_create (face);
/* The size: one pixel is 64 units, so positions keep fractions of a pixel. */
int size = atoi (argv[3]) * 64;
hb_font_set_scale (font, size, size);
hb_buffer_t *buf = hb_buffer_create ();
hb_buffer_add_utf8 (buf, argv[2], -1, 0, -1);
hb_buffer_guess_segment_properties (buf);
hb_shape (font, buf, NULL, 0);
unsigned count;
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buf, &count);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (buf, &count);
/* The image: as wide as the line, and as tall as the font's ascender
* and descender, in whole pixels. */
int width = 0;
for (unsigned i = 0; i < count; i++) width += pos[i].x_advance;
hb_font_extents_t line;
hb_font_get_h_extents (font, &line);
int bottom = (line.descender - 63) / 64, top = (line.ascender + 63) / 64;
unsigned w = (width + 63) / 64, h = top - bottom;
hb_raster_extents_t extents = {0, bottom, w, h, 0};
/* Paint each glyph at its pen position, in black. */
hb_raster_paint_t *paint = hb_raster_paint_create_or_fail ();
hb_raster_paint_set_scale_factor (paint, 64, 64); /* 64 units to the pixel */
hb_raster_paint_set_extents (paint, &extents);
hb_raster_paint_set_foreground (paint, HB_COLOR (0, 0, 0, 255));
float x = 0, y = 0;
for (unsigned i = 0; i < count; i++)
{
hb_raster_paint_set_transform (paint, 1, 0, 0, 1,
x + pos[i].x_offset, y + pos[i].y_offset);
hb_raster_paint_glyph (paint, font, info[i].codepoint);
x += pos[i].x_advance;
y += pos[i].y_advance;
}
/* Write the PNG. */
hb_raster_image_t *image = hb_raster_paint_render (paint);
hb_blob_t *png = hb_raster_image_serialize_to_png_or_fail (image);
if (!png)
{
fprintf (stderr, "nothing to write\n");
return 1;
}
unsigned length;
const char *data = hb_blob_get_data (png, &length);
fwrite (data, 1, length, stdout);
hb_blob_destroy (png);
hb_raster_image_destroy (image);
hb_raster_paint_destroy (paint);
hb_buffer_destroy (buf);
hb_font_destroy (font);
hb_face_destroy (face);
hb_blob_destroy (blob);
return 0;
}
Three things change. The font now has a size, set with hb_font_set_scale to 64 units a pixel, so that positions keep fractions of a pixel, and hb_raster_paint_set_scale_factor tells the rasterizer to divide by 64 again. The image’s size has to be given before drawing: here it is the line’s advance by the font’s ascender and descender, in whole pixels. And it uses a paint context, not a draw context, because only a painted image can be written as PNG (hb_raster_image_serialize_to_png_or_fail takes only color images). Painting has a bonus: a color font comes out in color, with no change to the program. hb-raster explains both contexts.
It builds with harfbuzz-raster, and takes a size in pixels as well:
cc text-to-png.c $(pkg-config --cflags --libs harfbuzz-raster) -o text-to-png
./text-to-png LibreBaskerville.ttf "office coffee" 32 > office.png
If HarfBuzz was built without libpng, it prints “nothing to write”: Meson uses libpng only if it finds it, and says whether it did in the summary it prints at the end of meson setup.
HarfBuzz in C++
The three programs compile as C++ too, unchanged. C++ can also do the cleanup itself, with HarfBuzz’s header hb-cplusplus.hh. To use it in the first program:
- Include
hb-cplusplus.hhafterhb.h. - Hold each object HarfBuzz creates in an
hb::unique_ptr, as inhb::unique_ptr<hb_buffer_t> buf {hb_buffer_create ()};, and pass HarfBuzz’s functions its pointer,buf.get (), as inhb_shape (font.get (), buf.get (), NULL, 0);. - Delete the
hb_*_destroycalls: each object is destroyed when itsunique_ptrgoes out of scope, in the reverse order of creation, as the C program destroys them.
The drawing programs need hb-vector.h or hb-raster.h included before hb-cplusplus.hh, which only then knows their types. hb::shared_ptr is the same for an object with more than one owner.
HarfBuzz in JavaScript
harfbuzzjs is HarfBuzz compiled to WebAssembly, from the HarfBuzz project, with the C API wrapped in classes. It runs in Node and in browsers. Version 1.6.4, which these programs use, contains HarfBuzz 15.0.0, one release behind this book. It doesn’t include hb-vector or hb-raster, but it gives each glyph’s outline as SVG path data, which is enough for both jobs.
harfbuzzjs names follow HarfBuzz’s with one rule: drop hb_ and the object’s name, make the function a method of a class (Blob, Face, Font, Buffer), and write it in camelCase. So hb_buffer_guess_segment_properties (buf) is buffer.guessSegmentProperties(), and a position’s x_advance is xAdvance. The rule works both ways, and it is what to use to find a method in HarfBuzz’s documentation, or a HarfBuzz function in harfbuzzjs: harfbuzzjs’s own documentation doesn’t give the C names. A few names don’t follow it:
| harfbuzzjs | HarfBuzz |
|---|---|
addText |
hb_buffer_add_utf16, so clusters count UTF-16 code units |
glyphName |
hb_font_glyph_to_string, which gives gid and a number for a glyph without a name |
hExtents |
hb_font_get_h_extents |
face.upem |
hb_face_get_upem, as a property |
glyphToPath |
none: harfbuzzjs’s own, built on hb_font_draw_glyph |
Glyphs in JavaScript
examples/quick-start/js/text-to-glyphs.mjs// Shape a line of text with harfbuzzjs and print the glyphs, as hb-shape does.
// usage: node text-to-glyphs.mjs FONT TEXT
import fs from "node:fs";
import * as hb from "harfbuzzjs";
const [fontPath, text] = process.argv.slice(2);
// Load the font: file → blob → face → font.
const blob = new hb.Blob(fs.readFileSync(fontPath));
const face = new hb.Face(blob);
const font = new hb.Font(face);
// Shape: characters in, positioned glyphs out, in font units.
const buffer = new hb.Buffer();
buffer.addText(text);
buffer.guessSegmentProperties(); // script, language, direction
hb.shape(font, buffer);
// Print each glyph: name=cluster, @offset if it has one, +advance.
const infos = buffer.getGlyphInfos();
const positions = buffer.getGlyphPositions();
const glyphs = [];
for (let i = 0; i < infos.length; i++) {
const pos = positions[i];
const name = font.glyphName(infos[i].codepoint); // a glyph id, after shaping
let glyph = `${name}=${infos[i].cluster}`;
if (pos.xOffset || pos.yOffset) glyph += `@${pos.xOffset},${pos.yOffset}`;
glyph += `+${pos.xAdvance}`;
glyphs.push(glyph);
}
console.log(`[${glyphs.join("|")}]`);
[o=0+654|f_f_i=1+973|c=4+536|e=5+573|space=6+287|c=7+536|o=8+654|f_f=9+718|e=11+573|e=12+573]hb-shape printsIt is the C program’s three steps under other names: Blob, Face, Font, Buffer, and shape, then getGlyphInfos and getGlyphPositions for the result, and glyphName for each glyph’s name. JavaScript strings are UTF-16, and addText gives the text to HarfBuzz that way, so clusters here count UTF-16 code units: a character outside the Basic Multilingual Plane, such as an emoji, counts as two.
npm install harfbuzzjs
node text-to-glyphs.mjs LibreBaskerville.ttf "office coffee"
SVG
examples/quick-start/js/text-to-svg.mjs// Shape a line of text with harfbuzzjs and draw it as SVG.
// usage: node text-to-svg.mjs FONT TEXT > out.svg
import fs from "node:fs";
import * as hb from "harfbuzzjs";
const [fontPath, text] = process.argv.slice(2);
// Load the font: file → blob → face → font.
const blob = new hb.Blob(fs.readFileSync(fontPath));
const face = new hb.Face(blob);
const font = new hb.Font(face);
// Shape: characters in, positioned glyphs out, in font units.
const buffer = new hb.Buffer();
buffer.addText(text);
buffer.guessSegmentProperties(); // script, language, direction
hb.shape(font, buffer);
// Draw each glyph's outline as an SVG path at its pen position.
const infos = buffer.getGlyphInfos();
const positions = buffer.getGlyphPositions();
let x = 0, y = 0, paths = "";
for (let i = 0; i < infos.length; i++) {
const pos = positions[i];
const d = font.glyphToPath(infos[i].codepoint); // a glyph id, after shaping
const at = `translate(${x + pos.xOffset},${y + pos.yOffset})`;
if (d) paths += `<path transform="${at}" d="${d}"/>\n`;
x += pos.xAdvance;
y += pos.yAdvance;
}
// The box: the line's advance, and the font's ascender and descender.
const { ascender, descender } = font.hExtents();
const viewBox = `0 ${-ascender} ${x} ${ascender - descender}`;
console.log(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`);
console.log(`<g transform="scale(1,-1)">\n${paths}</g>\n</svg>`);
The first half is the same. Drawing is done by hand: glyphToPath returns a glyph’s outline as path data in font units, with y going up, and each path is moved to its pen position. SVG’s y goes down, so the whole line is flipped with scale(1,-1). The box is the line’s advance by the font’s ascender and descender.
node text-to-svg.mjs LibreBaskerville.ttf "office coffee" > office.svg
Pixels, in a browser
In a browser, the canvas does the rasterizing: the same path data becomes a Path2D, and the canvas fills it. This module exports one function, drawText, which shapes a line and draws it on a canvas:
examples/quick-start/js/text-to-canvas.mjs// Draw a line of text on a <canvas>: harfbuzzjs shapes it, and the browser
// fills the glyphs' outlines.
import * as hb from "harfbuzzjs";
export function drawText(canvas, fontData, text, pixels) {
// Load the font and shape the text, in font units.
const font = new hb.Font(new hb.Face(new hb.Blob(fontData)));
const buffer = new hb.Buffer();
buffer.addText(text);
buffer.guessSegmentProperties();
hb.shape(font, buffer);
// Size the canvas: the line's advance, and the font's ascender and
// descender, turned from font units into pixels.
const scale = pixels / font.face.upem;
const { ascender, descender } = font.hExtents();
const positions = buffer.getGlyphPositions();
let width = 0;
for (let i = 0; i < positions.length; i++) width += positions[i].xAdvance;
const top = Math.ceil(ascender * scale);
const bottom = Math.floor(descender * scale);
canvas.width = Math.ceil(width * scale);
canvas.height = top - bottom;
// Draw in font units, y up, with the baseline below the ascender.
const ctx = canvas.getContext("2d");
ctx.translate(0, top);
ctx.scale(scale, -scale);
// Fill each glyph's outline at its pen position.
const infos = buffer.getGlyphInfos();
let x = 0, y = 0;
for (let i = 0; i < infos.length; i++) {
const pos = positions[i];
ctx.save();
ctx.translate(x + pos.xOffset, y + pos.yOffset);
ctx.fill(new Path2D(font.glyphToPath(infos[i].codepoint)));
ctx.restore();
x += pos.xAdvance;
y += pos.yAdvance;
}
}
A canvas can be scaled and flipped once, so the glyphs are drawn in font units with y going up, and the canvas turns them into pixels.
A web page uses the module like this:
examples/quick-start/js/text-to-canvas.html<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>office coffee</title>
<!-- Where the browser finds harfbuzzjs when a module imports "harfbuzzjs". -->
<script type="importmap">
{ "imports": { "harfbuzzjs": "https://cdn.jsdelivr.net/npm/harfbuzzjs@1.6.4/dist/index.mjs" } }
</script>
<canvas id="line"></canvas>
<script type="module">
import { drawText } from "./text-to-canvas.mjs";
// The font's bytes, from beside the page.
const response = await fetch("LibreBaskerville.ttf");
const font = new Uint8Array(await response.arrayBuffer());
// 32 CSS pixels high, with as many canvas pixels as the screen has.
const canvas = document.getElementById("line");
const ratio = window.devicePixelRatio || 1;
drawText(canvas, font, "office coffee", 32 * ratio);
canvas.style.width = canvas.width / ratio + "px";
</script>
</html>
The page, text-to-canvas.mjs, and the font go in one folder. The import map tells the browser where to find a module imported by a bare name: when text-to-canvas.mjs imports "harfbuzzjs", the browser loads harfbuzzjs 1.6.4 from jsDelivr, a CDN that serves npm packages, so nothing has to be installed. To serve harfbuzzjs yourself, copy index.mjs, harfbuzz.js, and harfbuzz.wasm from node_modules/harfbuzzjs/dist/ into a folder named harfbuzzjs beside the page, and change the import map to "./harfbuzzjs/index.mjs". harfbuzzjs loads harfbuzz.wasm from beside its own module, wherever that is.
On a high-resolution screen, the canvas should have more pixels than it takes up on the page, devicePixelRatio times as many, or the text comes out blurred. The page asks drawText for that many pixels, and then sets the canvas’s width in CSS pixels.
Browsers don’t run modules from a page opened as a file, so serve the folder with a local web server, such as Python’s:
python3 -m http.server
and open http://localhost:8000/text-to-canvas.html.
Raster · canvas Drawn in your browser, by the program above. The font is LibreBaskerville.ttf, cut down to the characters 20-7E (hex).
The web edition of this book runs this program on the page, with a box to type text into.
HarfBuzz in Python
uharfbuzz is HarfBuzz’s Python binding, from the HarfBuzz project, and comes ready-built for the common platforms. Version 0.57.0, which these programs use, contains HarfBuzz 15.0.0, one release behind this book. Unlike harfbuzzjs, it includes hb-raster, though not hb-vector.
uharfbuzz keeps HarfBuzz’s names, in snake_case, without the hb_ and the object’s name, and turns getters into properties (buf.glyph_infos, face.upem). Each function’s documentation links to the C function it wraps. Two names differ: add_str is hb_buffer_add_utf32, and draw_glyph_with_pen is hb_font_draw_glyph with a fontTools-style pen.
Glyphs in Python
examples/quick-start/python/text-to-glyphs.py# Shape a line of text with uharfbuzz and print the glyphs, as hb-shape does.
# usage: python text-to-glyphs.py FONT TEXT
import sys
import uharfbuzz as hb
font_path, text = sys.argv[1], sys.argv[2]
# Load the font: file → blob → face → font.
blob = hb.Blob.from_file_path(font_path)
face = hb.Face(blob)
font = hb.Font(face)
# Shape: characters in, positioned glyphs out, in font units.
buf = hb.Buffer()
buf.add_str(text)
buf.guess_segment_properties() # script, language, direction
hb.shape(font, buf)
# Print each glyph: name=cluster, @offset if it has one, +advance.
glyphs = []
for info, pos in zip(buf.glyph_infos, buf.glyph_positions):
name = font.glyph_to_string(info.codepoint) # a glyph id, after shaping
offset = f"@{pos.x_offset},{pos.y_offset}" if pos.x_offset or pos.y_offset else ""
glyphs.append(f"{name}={info.cluster}{offset}+{pos.x_advance}")
print("[" + "|".join(glyphs) + "]")
[o=0+654|f_f_i=1+973|c=4+536|e=5+573|space=6+287|c=7+536|o=8+654|f_f=9+718|e=11+573|e=12+573]hb-shape printsThe same steps under Python names: Blob, Face, Font, Buffer, and shape, then glyph_infos and glyph_positions for the result, and glyph_to_string for each glyph’s name. add_str gives the text to HarfBuzz as UTF-32, so clusters here count characters, as hb-shape’s do.
pip install uharfbuzz
python text-to-glyphs.py LibreBaskerville.ttf "office coffee"
For type designers: this is the program to try with a font of your own. Put the shaping and printing in a loop over the lines of a word list, and it shapes thousands of words in a second. From there a test is a short step: compare each line with what it printed for the last version of the font, and every word whose glyphs or advances have changed stands out. HarfBuzz’s own shaping tests work the same way: a font, some text, and the glyphs expected.
SVG
examples/quick-start/python/text-to-svg.py# Shape a line of text with uharfbuzz and draw it as SVG.
# usage: python text-to-svg.py FONT TEXT > out.svg
import sys
import uharfbuzz as hb
class SvgPen:
"""Collects one glyph's outline as SVG path data, in font units, y up."""
def __init__(self):
self.d = []
def moveTo(self, p):
self.d.append(f"M{p[0]:g},{p[1]:g}")
def lineTo(self, p):
self.d.append(f"L{p[0]:g},{p[1]:g}")
def qCurveTo(self, c, p):
self.d.append(f"Q{c[0]:g},{c[1]:g} {p[0]:g},{p[1]:g}")
def curveTo(self, c1, c2, p):
self.d.append(f"C{c1[0]:g},{c1[1]:g} {c2[0]:g},{c2[1]:g} {p[0]:g},{p[1]:g}")
def closePath(self):
self.d.append("Z")
font_path, text = sys.argv[1], sys.argv[2]
# Load the font: file → blob → face → font.
blob = hb.Blob.from_file_path(font_path)
face = hb.Face(blob)
font = hb.Font(face)
# Shape: characters in, positioned glyphs out, in font units.
buf = hb.Buffer()
buf.add_str(text)
buf.guess_segment_properties() # script, language, direction
hb.shape(font, buf)
# Draw each glyph's outline as an SVG path at its pen position.
infos = buf.glyph_infos
positions = buf.glyph_positions
x = y = 0
paths = ""
for i in range(len(infos)):
pos = positions[i]
pen = SvgPen()
font.draw_glyph_with_pen(infos[i].codepoint, pen) # a glyph id, after shaping
if pen.d:
at = f"translate({x + pos.x_offset},{y + pos.y_offset})"
paths += f'<path transform="{at}" d="{" ".join(pen.d)}"/>\n'
x += pos.x_advance
y += pos.y_advance
# The box: the line's advance, and the font's ascender and descender.
extents = font.get_font_extents("ltr")
asc, desc = extents.ascender, extents.descender
print(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 {-asc} {x} {asc - desc}">')
print(f'<g transform="scale(1,-1)">\n{paths}</g>\n</svg>')
The first half is the same. draw_glyph_with_pen sends a glyph’s outline to a pen, an object whose moveTo, lineTo, qCurveTo, curveTo, and closePath methods are called with each point, in font units and y up. It is the same kind of pen fontTools uses, so a fontTools pen works here too. This one collects the outline as SVG path data, and the rest is as in JavaScript.
python text-to-svg.py LibreBaskerville.ttf "office coffee" > office.svg
PNG with hb-raster
Because uharfbuzz includes hb-raster, the PNG version can do what the C program does: give the font a size, paint each glyph with a RasterPaint, and render the image. hb-raster’s image comes back as raw pixels, so Pillow, Python’s usual imaging library, writes the PNG:
examples/quick-start/python/text-to-png.py# Shape a line of text with uharfbuzz, paint it with hb-raster, and save it
# as a PNG with Pillow.
# usage: python text-to-png.py FONT TEXT PIXELS > out.png
import math
import sys
import uharfbuzz as hb
from PIL import Image
font_path, text, pixels = sys.argv[1], sys.argv[2], int(sys.argv[3])
blob = hb.Blob.from_file_path(font_path)
face = hb.Face(blob)
font = hb.Font(face)
# The size: one pixel is 64 units, so positions keep fractions of a pixel.
font.scale = (pixels * 64, pixels * 64)
buf = hb.Buffer()
buf.add_str(text)
buf.guess_segment_properties()
hb.shape(font, buf)
infos = buf.glyph_infos
positions = buf.glyph_positions
# The image: as wide as the line, and as tall as the font's ascender and
# descender, in whole pixels.
width = 0
for pos in positions:
width += pos.x_advance
extents = font.get_font_extents("ltr")
top = math.ceil(extents.ascender / 64)
bottom = math.floor(extents.descender / 64)
# Paint each glyph at its pen position, in black, the default.
paint = hb.RasterPaint()
paint.scale_factor = (64, 64) # 64 units to the pixel
paint.extents = hb.RasterExtents(0, bottom, math.ceil(width / 64), top - bottom, 0)
x = y = 0
for i in range(len(infos)):
pos = positions[i]
paint.transform = (1, 0, 0, 1, x + pos.x_offset, y + pos.y_offset)
paint.paint_glyph(font, infos[i].codepoint)
x += pos.x_advance
y += pos.y_advance
# hb-raster gives premultiplied BGRA pixels, rows bottom to top; Pillow
# turns them into a PNG.
image = paint.render()
e = image.extents
png = Image.frombuffer("RGBA", (e.width, e.height), image.buffer, "raw", "BGRa", e.stride, -1)
png.save(sys.stdout.buffer, "PNG")
The pixels are blue, green, red, and alpha, premultiplied, with the rows from the bottom up (hb-raster); Pillow’s BGRa mode and a negative stride, the -1, take them as they are.
pip install uharfbuzz pillow
python text-to-png.py LibreBaskerville.ttf "office coffee" 32 > office.png
HarfBuzz in Rust: HarfRust
Rust programs usually don’t call HarfBuzz itself. They use HarfRust, a port of HarfBuzz’s shaping to Rust, which matches HarfBuzz 15.2.0 but isn’t HarfBuzz: HarfRust counts the differences. It only shapes, so the outlines come from Skrifa, part of the same Rust font libraries (Fontations). For C HarfBuzz itself, the harfbuzz crate has bindings, but they are less used.
HarfRust’s API is its own, modeled on HarfBuzz’s but not a binding to it, so its names don’t map one to one. The difference most worth knowing: C’s codepoint field, which holds a glyph ID after shaping, is glyph_id in HarfRust.
The project’s Cargo.toml asks for harfrust = "0.16.0", which is all the first program needs, and for the drawing programs skrifa = "0.50.0", and tiny-skia for the PNG version.
Glyphs with HarfRust
examples/quick-start/rust/src/text-to-glyphs.rs// Shape a line of text with HarfRust and print the glyphs, as hb-shape does.
// usage: text-to-glyphs FONT TEXT
use harfrust::{Buffer, Font, GlyphId, ShapeOptions, ShaperFont};
fn main() {
let args: Vec<String> = std::env::args().collect();
let [_, font_path, text] = args.as_slice() else {
panic!("usage: text-to-glyphs FONT TEXT");
};
let data = std::fs::read(font_path).expect("can't read the font");
// Shape: characters in, positioned glyphs out, in font units.
let font = Font::new(data, 0).expect("not a font");
let mut buffer = Buffer::new();
buffer.push_str(text);
buffer.guess_segment_properties(); // script, language, direction
let shaper_font = ShaperFont::new(&font);
let options = ShapeOptions::new();
harfrust::shape(&shaper_font, &mut buffer, options).expect("shaping failed");
// Print each glyph: name=cluster, @offset if it has one, +advance.
let infos = buffer.glyph_infos();
let positions = buffer.glyph_positions();
let mut glyphs = Vec::new();
for i in 0..infos.len() {
let pos = &positions[i];
let name = match shaper_font.glyph_name(GlyphId::new(infos[i].glyph_id)) {
Some(name) => name.to_string(),
None => format!("gid{}", infos[i].glyph_id),
};
let mut glyph = format!("{}={}", name, infos[i].cluster);
if pos.x_offset != 0 || pos.y_offset != 0 {
glyph += &format!("@{},{}", pos.x_offset, pos.y_offset);
}
glyph += &format!("+{}", pos.x_advance);
glyphs.push(glyph);
}
println!("[{}]", glyphs.join("|"));
}
[o=0+654|f_f_i=1+973|c=4+536|e=5+573|space=6+287|c=7+536|o=8+654|f_f=9+718|e=11+573|e=12+573]hb-shape printsThe same steps again, with one fewer name: HarfRust’s Font reads the file’s bytes itself, with no blob or face, and a ShaperFont is what shapes with it. HarfRust has no font size at all: it always shapes in font units, and a program scales the result. glyph_name gives a glyph’s name if the font has one. push_str sets each cluster to its character’s byte offset in the UTF-8 string, so clusters count bytes, as the C program’s do. Here the build’s check says something more than in the other languages: a different shaper has produced the same glyphs, clusters, and advances as HarfBuzz.
cargo run --release --bin text-to-glyphs -- LibreBaskerville.ttf "office coffee"
SVG with HarfRust and Skrifa
examples/quick-start/rust/src/text-to-svg.rs// Shape a line of text with HarfRust and draw it as SVG with Skrifa.
// usage: text-to-svg FONT TEXT > out.svg
use harfrust::{Buffer, Font, ShapeOptions, ShaperFont};
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{pen::SvgPen, DrawSettings};
use skrifa::{FontRef, GlyphId, MetadataProvider};
fn main() {
let args: Vec<String> = std::env::args().collect();
let [_, font_path, text] = args.as_slice() else {
panic!("usage: text-to-svg FONT TEXT");
};
let data = std::fs::read(font_path).expect("can't read the font");
// Shape: characters in, positioned glyphs out, in font units.
let font = Font::new(data.clone(), 0).expect("not a font");
let mut buffer = Buffer::new();
buffer.push_str(text);
buffer.guess_segment_properties(); // script, language, direction
let shaper_font = ShaperFont::new(&font);
let options = ShapeOptions::new();
harfrust::shape(&shaper_font, &mut buffer, options).expect("shaping failed");
// Draw each glyph's outline as an SVG path at its pen position.
let skrifa_font = FontRef::new(&data).expect("not a font");
let outlines = skrifa_font.outline_glyphs();
let mut x = 0;
let mut y = 0;
let mut paths = String::new();
let infos = buffer.glyph_infos();
let positions = buffer.glyph_positions();
for i in 0..infos.len() {
let glyph_id = GlyphId::new(infos[i].glyph_id);
let pos = &positions[i];
let mut pen = SvgPen::new();
if let Some(glyph) = outlines.get(glyph_id) {
let size = Size::unscaled(); // font units
let settings = DrawSettings::unhinted(size, LocationRef::default());
glyph.draw(settings, &mut pen).expect("can't draw");
}
paths += &format!(
"<path transform=\"translate({},{})\" d=\"{}\"/>\n",
x + pos.x_offset, y + pos.y_offset, pen
);
x += pos.x_advance;
y += pos.y_advance;
}
// The box: the line's advance, and the font's ascender and descender.
let metrics = skrifa_font.metrics(Size::unscaled(), LocationRef::default());
let top = metrics.ascent;
let bottom = metrics.descent;
println!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 {} {} {}\">",
-top, x, top - bottom
);
print!("<g transform=\"scale(1,-1)\">\n{paths}</g>\n</svg>\n");
}
The first half is the same. Skrifa’s SvgPen collects one glyph’s outline as path data, and the program writes the rest of the SVG as the JavaScript did.
cargo run --release --bin text-to-svg -- LibreBaskerville.ttf "office coffee" > office.svg
PNG with tiny-skia
For pixels, Skrifa draws each outline at the size wanted, and tiny-skia, a small rasterizer, fills it:
examples/quick-start/rust/src/text-to-png.rs// Shape a line of text with HarfRust, and draw it as a PNG with Skrifa's
// outlines and tiny-skia's rasterizer.
// usage: text-to-png FONT TEXT PIXELS > out.png
use harfrust::{Buffer, Font, ShapeOptions, ShaperFont};
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::{FontRef, GlyphId, MetadataProvider};
use std::io::Write;
use tiny_skia::{FillRule, Paint, PathBuilder, Pixmap, Transform};
// A pen that turns outline commands, which are y-up, into a tiny-skia path,
// which is y-down, moved to (x, y) in pixels.
struct Pen { path: PathBuilder, x: f32, y: f32 }
impl OutlinePen for Pen {
fn move_to(&mut self, x: f32, y: f32) { self.path.move_to(self.x + x, self.y - y) }
fn line_to(&mut self, x: f32, y: f32) { self.path.line_to(self.x + x, self.y - y) }
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
self.path.quad_to(self.x + x1, self.y - y1, self.x + x, self.y - y)
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
self.path.cubic_to(self.x + x1, self.y - y1, self.x + x2, self.y - y2,
self.x + x, self.y - y)
}
fn close(&mut self) { self.path.close() }
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let [_, font_path, text, pixels] = args.as_slice() else {
panic!("usage: text-to-png FONT TEXT PIXELS");
};
let pixels: f32 = pixels.parse().expect("PIXELS must be a number");
let data = std::fs::read(font_path).expect("can't read the font");
// Shape, in font units: HarfRust has no font size.
let font = Font::new(data.clone(), 0).expect("not a font");
let mut buffer = Buffer::new();
buffer.push_str(text);
buffer.guess_segment_properties();
let shaper_font = ShaperFont::new(&font);
let options = ShapeOptions::new();
harfrust::shape(&shaper_font, &mut buffer, options).expect("shaping failed");
// Font units to pixels.
let skrifa_font = FontRef::new(&data).expect("not a font");
let size = Size::new(pixels);
let scale = pixels / font.units_per_em() as f32;
let metrics = skrifa_font.metrics(size, LocationRef::default());
// The image: as wide as the line, as tall as the ascender and descender.
let mut advance = 0;
for pos in buffer.glyph_positions() {
advance += pos.x_advance;
}
let width = (advance as f32 * scale).ceil() as u32;
let top = metrics.ascent.ceil();
let bottom = metrics.descent.floor();
let height = (top - bottom) as u32;
let baseline = top;
// One path for the whole line, each glyph drawn at its pen position.
let outlines = skrifa_font.outline_glyphs();
let mut pen = Pen { path: PathBuilder::new(), x: 0.0, y: 0.0 };
let mut x = 0;
let mut y = 0;
let infos = buffer.glyph_infos();
let positions = buffer.glyph_positions();
for i in 0..infos.len() {
let glyph_id = GlyphId::new(infos[i].glyph_id);
let pos = &positions[i];
pen.x = (x + pos.x_offset) as f32 * scale;
pen.y = baseline - (y + pos.y_offset) as f32 * scale;
if let Some(glyph) = outlines.get(glyph_id) {
let settings = DrawSettings::unhinted(size, LocationRef::default());
glyph.draw(settings, &mut pen).expect("can't draw");
}
x += pos.x_advance;
y += pos.y_advance;
}
// Fill it in black, on a transparent background, and write the PNG.
let mut pixmap = Pixmap::new(width, height).expect("empty image");
if let Some(path) = pen.path.finish() {
let mut paint = Paint::default();
paint.set_color_rgba8(0, 0, 0, 255);
let transform = Transform::identity();
pixmap.fill_path(&path, &paint, FillRule::Winding, transform, None);
}
let png = pixmap.encode_png().expect("can't encode PNG");
std::io::stdout().write_all(&png).unwrap();
}
The pen is the only new part. Skrifa calls a pen’s move_to, line_to, quad_to, curve_to, and close with each point of the outline, y up and already scaled to pixels; this one adds the glyph’s position and turns y down, and builds one path for the whole line. It sizes its image as the C program does, and the two PNGs come out the same size.
What these programs leave out
They are as short as they can be, and a real program needs more. In rough order of how soon it matters:
- Script, language, and direction, set from what the application knows, not guessed. A string that mixes scripts or directions has to be split into runs first, each shaped on its own (Why shaping exists).
- Features, such as small caps or old-style figures, passed to
hb_shape(From features to lookups). - Fallback fonts. A glyph ID of 0 means the font has no glyph for a character, and the application should find a font that does.
- Line breaking. HarfBuzz shapes a line; deciding where lines end is the application’s job, helped by the safe-to-break flags (For applications).
- Variable fonts, set to a position with
hb_font_set_variations(The design space). - Hinting and small sizes. hb-raster and tiny-skia don’t hint. For hinted text, FreeType draws the outlines (hb-raster explains the trade).
- Color fonts. The C and Python PNG programs paint them already, since they paint with hb-raster. The SVG programs would need hb-vector’s paint context in C, or a color library in the other languages (Color).
- Checking the font. HarfBuzz doesn’t fail on a file that isn’t a font (Before shipping says what happens, and what to check).
For a real program, two places take over from here. HarfBuzz’s user manual explains how to do each of the things above. Before shipping, at the end of For applications, lists the same steps with links to both the manual and this book, and the traps that a program built on these examples can still fall into.
Documentation
Each library’s own reference is where to go next:
| Language | Library | Reference |
|---|---|---|
| C | HarfBuzz | the API reference, including buffers, hb-vector, and hb-raster |
| JavaScript | harfbuzzjs | its README, and the type declarations in dist/index.d.mts |
| Python | uharfbuzz, Pillow | uharfbuzz’s documentation, and Pillow’s |
| Rust | HarfRust, Skrifa, tiny-skia | HarfRust, Skrifa, and tiny-skia on docs.rs |
Where to read the source
| File | What it shows |
|---|---|
examples/quick-start/ (in the book’s repository) |
the programs on this page, with the JavaScript package.json, the Python requirements.txt, and the Rust Cargo.toml |
util/hb-shape.cc, util/shape-format.hh |
how hb-shape prints: the C glyphs program, with options |
util/vector-output.hh |
how hb-vector draws: the C SVG program, with options |
util/raster-output.hh |
how hb-raster draws, including its image sizes and margins |
src/hb-vector.h, src/hb-raster.h |
the drawing libraries’ API |
docs/usermanual-getting-started.xml |
HarfBuzz’s own first program, which shapes and prints the glyphs |
In short
- Every program does the same three things first: load the font (blob, face, font), shape the text in a buffer, and read the glyphs, with their clusters, advances, and offsets.
- The smallest program stops there and prints them, as
hb-shapedoes. It needs only HarfBuzz itself, in any recent version. - Clusters count in the units the text was given in: bytes in C and Rust, UTF-16 code units in JavaScript, characters in Python.
- A drawing program walks the glyphs, adding up advances and offsets, and draws each at its pen position.
- In C, hb-vector draws the glyphs as SVG and hb-raster as pixels.
- In JavaScript, harfbuzzjs shapes, and gives outlines as SVG path data, for an SVG file or a canvas.
- In Python, uharfbuzz shapes, draws outlines through a pen, and paints with hb-raster; Pillow writes the PNG.
- In Rust, HarfRust shapes, Skrifa gives the outlines, and a rasterizer such as tiny-skia makes pixels. HarfRust is a port, not HarfBuzz.
- Real programs also set script, language, and direction, split mixed text into runs, choose fallback fonts, and break lines.