Python interface for cairo graphics library providing 2D vector graphics, drawing operations, and rendering to multiple output formats
npx @tessl/cli install tessl/pypi-pycairo@1.28.00
# Pycairo
1
2
Pycairo is a comprehensive Python binding library for the Cairo graphics library that provides an object-oriented interface for creating vector graphics, handling 2D drawing operations, and rendering to multiple output formats including SVG, PDF, PNG, and PostScript. The library maintains close compatibility with the Cairo C API while offering Pythonic enhancements, automatic error handling through exceptions, and support for advanced graphics operations like transformations, patterns, gradients, and text rendering.
3
4
## Package Information
5
6
- **Package Name**: pycairo
7
- **Language**: Python
8
- **Installation**: `pip install pycairo`
9
- **Python Version**: 3.9+
10
- **Dependencies**: Cairo graphics library (>= 1.15.10)
11
12
## Core Imports
13
14
```python
15
import cairo
16
```
17
18
Create drawing contexts and surfaces:
19
20
```python
21
# Create surfaces for different output formats
22
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
23
pdf_surface = cairo.PDFSurface("output.pdf", width, height)
24
svg_surface = cairo.SVGSurface("output.svg", width, height)
25
26
# Create drawing context
27
context = cairo.Context(surface)
28
```
29
30
## Basic Usage
31
32
```python
33
import cairo
34
35
# Create an image surface (in-memory bitmap)
36
width, height = 400, 300
37
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
38
context = cairo.Context(surface)
39
40
# Set background color
41
context.set_source_rgb(1, 1, 1) # White background
42
context.paint()
43
44
# Draw a blue rectangle
45
context.set_source_rgb(0, 0, 1) # Blue color
46
context.rectangle(50, 50, 200, 100)
47
context.fill()
48
49
# Draw a red circle
50
context.set_source_rgb(1, 0, 0) # Red color
51
context.arc(300, 150, 50, 0, 2 * 3.14159)
52
context.fill()
53
54
# Add some text
55
context.set_source_rgb(0, 0, 0) # Black color
56
context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
57
context.set_font_size(20)
58
context.move_to(50, 200)
59
context.show_text("Hello Cairo!")
60
61
# Save to PNG file
62
surface.write_to_png("example.png")
63
```
64
65
## Architecture
66
67
Pycairo follows the Cairo architecture with key components:
68
69
- **Surface**: Output targets (image buffers, PDF, SVG, PNG files, etc.)
70
- **Context**: Drawing state and operations (current path, colors, transformations)
71
- **Pattern**: Paint sources (solid colors, gradients, images)
72
- **Path**: Vector path data for shapes and strokes
73
- **Matrix**: 2D transformations (scaling, rotation, translation)
74
- **FontFace**: Font resources and text rendering
75
76
The library provides both high-level convenience functions and low-level control over every aspect of the rendering pipeline, making it suitable for everything from simple graphics to complex scientific visualizations.
77
78
## Capabilities
79
80
### Drawing Context Operations
81
82
The Context class provides the primary interface for all drawing operations including path construction, filling, stroking, clipping, and transformation management.
83
84
```python { .api }
85
class Context:
86
def __init__(self, target: Surface) -> None: ...
87
def save(self) -> None: ...
88
def restore(self) -> None: ...
89
def set_source_rgb(self, red: float, green: float, blue: float) -> None: ...
90
def set_source_rgba(self, red: float, green: float, blue: float, alpha: float) -> None: ...
91
def rectangle(self, x: float, y: float, width: float, height: float) -> None: ...
92
def arc(self, xc: float, yc: float, radius: float, angle1: float, angle2: float) -> None: ...
93
def move_to(self, x: float, y: float) -> None: ...
94
def line_to(self, x: float, y: float) -> None: ...
95
def fill(self) -> None: ...
96
def stroke(self) -> None: ...
97
def paint(self) -> None: ...
98
```
99
100
[Drawing Context](./drawing-context.md)
101
102
### Surface Classes and Output Formats
103
104
Surface classes provide rendering targets for different output formats including in-memory images, PDF documents, SVG graphics, and PostScript files.
105
106
```python { .api }
107
class Surface:
108
def finish(self) -> None: ...
109
def flush(self) -> None: ...
110
def get_content(self) -> Content: ...
111
112
class ImageSurface(Surface):
113
def __init__(self, format: Format, width: int, height: int) -> None: ...
114
def write_to_png(self, filename: str) -> None: ...
115
116
class PDFSurface(Surface):
117
def __init__(self, filename: str, width_in_points: float, height_in_points: float) -> None: ...
118
119
class SVGSurface(Surface):
120
def __init__(self, filename: str, width_in_points: float, height_in_points: float) -> None: ...
121
```
122
123
[Surfaces](./surfaces.md)
124
125
### Pattern Classes for Paint Sources
126
127
Pattern classes define paint sources for filling and stroking operations, including solid colors, gradients, and image-based patterns.
128
129
```python { .api }
130
class Pattern:
131
def get_extend(self) -> Extend: ...
132
def set_extend(self, extend: Extend) -> None: ...
133
134
class SolidPattern(Pattern):
135
def __init__(self, red: float, green: float, blue: float, alpha: float = 1.0) -> None: ...
136
137
class LinearGradient(Pattern):
138
def __init__(self, x0: float, y0: float, x1: float, y1: float) -> None: ...
139
def add_color_stop_rgb(self, offset: float, red: float, green: float, blue: float) -> None: ...
140
141
class RadialGradient(Pattern):
142
def __init__(self, cx0: float, cy0: float, radius0: float, cx1: float, cy1: float, radius1: float) -> None: ...
143
```
144
145
[Patterns](./patterns.md)
146
147
### Geometry Classes for Shapes and Transformations
148
149
Classes for handling geometric data including vector paths, transformation matrices, rectangles, and regions.
150
151
```python { .api }
152
class Path:
153
def __iter__(self) -> Iterator[tuple[PathDataType, tuple[float, ...]]]: ...
154
155
class Matrix:
156
def __init__(self, xx: float = 1.0, yx: float = 0.0, xy: float = 0.0, yy: float = 1.0, x0: float = 0.0, y0: float = 0.0) -> None: ...
157
def rotate(self, radians: float) -> None: ...
158
def scale(self, sx: float, sy: float) -> None: ...
159
def translate(self, tx: float, ty: float) -> None: ...
160
161
class Rectangle:
162
def __init__(self, x: float, y: float, width: float, height: float) -> None: ...
163
```
164
165
[Geometry](./geometry.md)
166
167
### Text and Font Rendering
168
169
Comprehensive text rendering capabilities including font selection, text measurement, and advanced typography features.
170
171
```python { .api }
172
class FontFace:
173
def __init__(self) -> None: ...
174
175
class FontOptions:
176
def __init__(self) -> None: ...
177
def set_antialias(self, antialias: Antialias) -> None: ...
178
def set_hint_style(self, hint_style: HintStyle) -> None: ...
179
180
class ScaledFont:
181
def __init__(self, font_face: FontFace, font_matrix: Matrix, ctm: Matrix, options: FontOptions) -> None: ...
182
def text_extents(self, text: str) -> TextExtents: ...
183
```
184
185
[Text and Fonts](./text-fonts.md)
186
187
### Constants and Enumerations
188
189
Comprehensive set of constants and enumeration types for controlling drawing parameters, format specifications, and rendering options.
190
191
```python { .api }
192
class Format:
193
INVALID: int
194
ARGB32: int
195
RGB24: int
196
A8: int
197
A1: int
198
199
class Antialias:
200
DEFAULT: int
201
NONE: int
202
GRAY: int
203
SUBPIXEL: int
204
205
# Version information
206
version: str
207
version_info: tuple[int, int, int]
208
CAIRO_VERSION: int
209
CAIRO_VERSION_STRING: str
210
```
211
212
[Constants and Enums](./constants-enums.md)
213
214
## Utility Functions
215
216
```python { .api }
217
def cairo_version() -> int:
218
"""Return encoded version of underlying C cairo library."""
219
220
def cairo_version_string() -> str:
221
"""Return human-readable version string of C cairo library."""
222
223
def get_include() -> str:
224
"""Return path to directory containing C header files for extensions."""
225
```
226
227
## Exception Handling
228
229
```python { .api }
230
class Error(Exception):
231
"""Base class for all cairo-related exceptions"""
232
pass
233
```
234
235
All Cairo operations that can fail will raise appropriate exceptions rather than return error codes, making error handling more Pythonic and robust.