Use a custom font with pycairo

143 Views Asked by At

I'm using Pycairo to draw images with text on it, with a custom font. This works well as long as that font is installed on the system.

However, I would like to distribute my package with my custom font attached as a data file (ttf or any other type), and to have my code refer to that file rather than assume the font is installed on the client's system.

In essence here's my code:

import cairo

with cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200) as surface:
    ctx = cairo.Context(surface)
    ctx.select_font_face("my-font")
    ctx.set_font_size(30)
    ctx.move_to(10, 50)
    ctx.show_text("Hello World")
    surface.write_to_png("hello.png")

Now instead of ctx.select_font_face("my-font"), I'd like to do something like ctx.select_font_face("./assets/my-font.ttf"). I've read Pycairo's doc about Text but I couldn't find any way to load a font from a file - it seems like only fonts installed on the system.

Is there a way to get Pycairo to load a font from a file?

1

There are 1 best solutions below

0
naved196 On

Use Python's ctypes module to load a font file using FreeType and create a cairo font face from it using the cairo-ft API which is not part of pycairo yet.

Refer the below link :- https://www.cairographics.org/cookbook/freetypepython/