[cairo] Building an SVG surface with shapes, text, and images together?

John Anderson sontek at gmail.com
Sun Sep 12 10:46:56 PDT 2010

I'm building a website using django and I want to generate an image
based on some elements in the database. I have text rendering just
fine but now I want to be able to add images as well but I can't find
much good documentation on doing this.

Here is what I have so far:

def view_event_design(request, event_id, design_id, surface_type):
    design = get_object_or_404(Design, pk=design_id)

    if surface_type == 'png':
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
design.width, design.height)
    elif surface_type == 'svg':
        output = StringIO.StringIO()
        surface = cairo.SVGSurface(output, design.width, design.height)

    context = cairo.Context(surface)

    context.scale(1, 1)

    # grab all elements, sorted by z
    elements = design.designelement_set.all().order_by('-z')

    # figure out if its a text or an image
    for element in elements:
        if element.designelementtext:
            text = element.designelementtext.text
            font_size = element.designelementtext.font_size
            font_face = element.designelementtext.font_face
            slant = cairo.FONT_SLANT_NORMAL
            weight = cairo.FONT_WEIGHT_NORMAL

            if element.designelementtext.is_bold:
                weight = cairo.FONT_WEIGHT_BOLD

            if element.designelementtext.is_italic:
                slant = cairo.FONT_SLANT_ITALIC

            rgb = hex_to_rgb(element.designelementtext.font_color)
            context.set_source_rgb (rgb[0], rgb[1], rgb[2])
            context.select_font_face(font_face, slant, weight)

            context.move_to (element.x, element.y + font_size)
            context.show_text (text)

        elif element.designelementimage:
            # How do I add an image to the surface?

    if surface_type == 'png':
        response = HttpResponse(mimetype='image/png')
    if surface_type == 'svg':
        response = HttpResponse(output.getvalue(), mimetype='image/svg+xml')

    return response

More information about the cairo mailing list