| 1 |
import cffi |
| 2 |
|
| 3 |
import cairocffi |
| 4 |
|
| 5 |
ffi = cffi.FFI() |
| 6 |
ffi.cdef(''' |
| 7 |
/* GLib */ |
| 8 |
typedef void cairo_t; |
| 9 |
typedef void* gpointer; |
| 10 |
void g_object_unref (gpointer object); |
| 11 |
|
| 12 |
/* Pango and PangoCairo */ |
| 13 |
typedef ... PangoLayout; |
| 14 |
typedef enum { |
| 15 |
PANGO_ALIGN_LEFT, |
| 16 |
PANGO_ALIGN_CENTER, |
| 17 |
PANGO_ALIGN_RIGHT |
| 18 |
} PangoAlignment; |
| 19 |
int pango_units_from_double (double d); |
| 20 |
PangoLayout * pango_cairo_create_layout (cairo_t *cr); |
| 21 |
void pango_cairo_show_layout (cairo_t *cr, PangoLayout *layout); |
| 22 |
void pango_layout_set_width (PangoLayout *layout, int width); |
| 23 |
void pango_layout_set_alignment ( |
| 24 |
PangoLayout *layout, PangoAlignment alignment); |
| 25 |
void pango_layout_set_markup ( |
| 26 |
PangoLayout *layout, const char *text, int length); |
| 27 |
''') |
| 28 |
gobject = ffi.dlopen('gobject-2.0') |
| 29 |
pango = ffi.dlopen('pango-1.0') |
| 30 |
pangocairo = ffi.dlopen('pangocairo-1.0') |
| 31 |
|
| 32 |
|
| 33 |
def gobject_ref(pointer): |
| 34 |
return ffi.gc(pointer, gobject.g_object_unref) |
| 35 |
|
| 36 |
|
| 37 |
units_from_double = pango.pango_units_from_double |
| 38 |
|
| 39 |
|
| 40 |
def write_example_pdf(target): |
| 41 |
pt_per_mm = 72 / 25.4 |
| 42 |
width, height = 210 * pt_per_mm, 297 * pt_per_mm # A4 portrait |
| 43 |
surface = cairocffi.PDFSurface(target, width, height) |
| 44 |
context = cairocffi.Context(surface) |
| 45 |
context.translate(0, 300) |
| 46 |
context.rotate(-0.2) |
| 47 |
|
| 48 |
layout = gobject_ref( |
| 49 |
pangocairo.pango_cairo_create_layout(context._pointer)) |
| 50 |
pango.pango_layout_set_width(layout, units_from_double(width)) |
| 51 |
pango.pango_layout_set_alignment(layout, pango.PANGO_ALIGN_CENTER) |
| 52 |
markup = '<span font="italic 30">Hi from Παν語!</span>' |
| 53 |
markup = ffi.new('char[]', markup.encode('utf8')) |
| 54 |
pango.pango_layout_set_markup(layout, markup, -1) |
| 55 |
pangocairo.pango_cairo_show_layout(context._pointer, layout) |
| 56 |
|
| 57 |
|
| 58 |
if __name__ == '__main__': |
| 59 |
write_example_pdf(target='pango_example.pdf') |