Hello World in pycairo

Cairo is a portable 2D graphics library for drawing to PDF, PNG, SVG, X11, Windows, etc. Here is a minimal example (hello world) to create a PNG with text on a solid background written in pycairo (Cairo for Python).

import cairo # import the Python module

# setup a place to draw
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 200)
ctx = cairo.Context (surface)

# paint background
ctx.set_source_rgb(0.22, 0.08, 0.69) # blue
ctx.rectangle(0, 0, 400, 200)

# draw text
ctx.set_font_size(60) # em-square height is 90 pixels
ctx.move_to(10, 90) # move to point (x, y) = (10, 90)
ctx.set_source_rgb(1.00, 0.83, 0.00) # yellow
ctx.show_text('Hello World')

# finish up
ctx.stroke() # commit to surface
surface.write_to_png('hello_world.png') # write to file

Hello World

This code was tested with PyCairo 1.8, Cairo 1.10, Python 2.7, and Fedora 14, but it should work on a variety of systems.

For more, see Cairo samples.

2 thoughts on “Hello World in pycairo

  1. There is one problem i’ve found. I can’t figure out what value should I use for text offset (y) when I making .move_to().
    If I choose ctx.move_to(0, 0) – part of text will be cropped.
    I think there are some evaluatable value for this offset.

    Do you know what it is?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s