Search⌘ K

Other Surfaces

Discover how to work with advanced Pycairo surface types like RecordingSurface, ScriptSurface, and TeeSurface. Learn to record, serialize, and duplicate drawing operations across different output formats, enabling efficient reuse and multi-format rendering in your graphics projects.

We'll cover the following...

RecordingSurface

A recording surface records drawing operations, which can later be played back to a normal surface. Here is an example of this:

Python 3.8
import cairo
# Recorded page
rec_surface = cairo.RecordingSurface(cairo.Content.COLOR, None)
ctx=cairo.Context(rec_surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
ctx.rectangle(100, 100, 200, 200)
ctx.set_source_rgb(1, 0, 0)
ctx.fill()
# Page 1
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 400)
ctx=cairo.Context(surface)
ctx.set_source_surface(rec_surface)
ctx.paint()
ctx.set_source_rgb(0, 0, 0)
ctx.move_to(500, 350)
ctx.set_font_size(20)
ctx.show_text('Page1')
surface.write_to_png('output/page1.png')
# Page 2
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 400)
ctx=cairo.Context(surface)
ctx.set_source_surface(rec_surface)
ctx.paint()
ctx.set_source_rgb(0, 0, 0)
ctx.move_to(500, 350)
ctx.set_font_size(20)
ctx.show_text('Page2')
surface.write_to_png('output/page2.png')

First, we create a RecordingSurface. This takes two parameters:

  • content defines the type of content we want to record. This is set by a cairo.Content value of COLOR, ALPHA, or COLOR_ALPHA (to record color and alpha information)

  • rectangle defines the area to record. Neither can be used to record all operations without bounds

Then, we then create a context and draw onto it in the usual ...