Michael Maclean

Handling fonts in PECL/Cairo

(This is just a quick note to get some information out there for reference, I am adding it to the PHP manual as well!)

Currently, in PECL/Cairo the only way to draw text is the referred to as the “toy” text API, which is a very basic way of handling text compared to the facilities available in the Cairo library itself. However, it’s sufficient for most purposes that I’ve come across so far. In version 0.1.0 of PECL/Cairo, there was only one way to choose what font you wished to use, which was the CairoContext::selectFontFace() method. You pass a string to this method with the name of the font you want, along with the optional slant and weight parameters. This then invokes your system’s font handling to find the font you’re after, or an alternative if it’s not available, so you need to have the font you want installed into your system’s font library. This is occasionally not handy.

In version 0.2.0 FreeType support was added. It allows you to choose any font file you’d like, as long as PHP’s streams API can find it. Yes, this means http:// streams, but I wouldn’t recommend it.

/* Set up the surface, and make the background white */
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 100);
$c = new CairoContext($s);
$c->setSourceRgb(1, 1, 1); 

/* Draw the text using the Vollkorn font, from 
   http://friedrichalthausen.de/2006/01/01/vollkorn/ */
$c->setSourceRGB(0, 0, 0);
$c->moveTo(10, 60);
$f = new CairoFtFontFace(dirname(__FILE__) . "/vollkorn.otf");
$c->showText("Hello world");

/* Send the image to the browser */
header("Content-type: image/png");

The output image should hopefully look like this:

Script output

(For those who are familiar with the Cairo library, this function maps to the cairo_ft_font_face_create_for_ft_face function in its API.)

There is still some work to be done in this area, notably to support the Windows and Mac OS X font systems, but they’ll be coming in a future release, we hope. If anyone would like to help us with that, or any other aspect of it (including documentation!), you can get in touch on the PECL dev mailing list, or if you’re on IRC, drop in to #php.pecl on EFnet. All contributions are welcome!