or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

constants-enums.mddrawing-context.mdgeometry.mdindex.mdpatterns.mdsurfaces.mdtext-fonts.md
tile.json

tessl/pypi-pycairo

Python interface for cairo graphics library providing 2D vector graphics, drawing operations, and rendering to multiple output formats

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pycairo@1.28.x

To install, run

npx @tessl/cli install tessl/pypi-pycairo@1.28.0

index.mddocs/

Pycairo

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.

Package Information

  • Package Name: pycairo
  • Language: Python
  • Installation: pip install pycairo
  • Python Version: 3.9+
  • Dependencies: Cairo graphics library (>= 1.15.10)

Core Imports

import cairo

Create drawing contexts and surfaces:

# Create surfaces for different output formats
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
pdf_surface = cairo.PDFSurface("output.pdf", width, height)
svg_surface = cairo.SVGSurface("output.svg", width, height)

# Create drawing context
context = cairo.Context(surface)

Basic Usage

import cairo

# Create an image surface (in-memory bitmap)
width, height = 400, 300
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
context = cairo.Context(surface)

# Set background color
context.set_source_rgb(1, 1, 1)  # White background
context.paint()

# Draw a blue rectangle
context.set_source_rgb(0, 0, 1)  # Blue color
context.rectangle(50, 50, 200, 100)
context.fill()

# Draw a red circle
context.set_source_rgb(1, 0, 0)  # Red color
context.arc(300, 150, 50, 0, 2 * 3.14159)
context.fill()

# Add some text
context.set_source_rgb(0, 0, 0)  # Black color
context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
context.set_font_size(20)
context.move_to(50, 200)
context.show_text("Hello Cairo!")

# Save to PNG file
surface.write_to_png("example.png")

Architecture

Pycairo follows the Cairo architecture with key components:

  • Surface: Output targets (image buffers, PDF, SVG, PNG files, etc.)
  • Context: Drawing state and operations (current path, colors, transformations)
  • Pattern: Paint sources (solid colors, gradients, images)
  • Path: Vector path data for shapes and strokes
  • Matrix: 2D transformations (scaling, rotation, translation)
  • FontFace: Font resources and text rendering

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.

Capabilities

Drawing Context Operations

The Context class provides the primary interface for all drawing operations including path construction, filling, stroking, clipping, and transformation management.

class Context:
    def __init__(self, target: Surface) -> None: ...
    def save(self) -> None: ...
    def restore(self) -> None: ...
    def set_source_rgb(self, red: float, green: float, blue: float) -> None: ...
    def set_source_rgba(self, red: float, green: float, blue: float, alpha: float) -> None: ...
    def rectangle(self, x: float, y: float, width: float, height: float) -> None: ...
    def arc(self, xc: float, yc: float, radius: float, angle1: float, angle2: float) -> None: ...
    def move_to(self, x: float, y: float) -> None: ...
    def line_to(self, x: float, y: float) -> None: ...
    def fill(self) -> None: ...
    def stroke(self) -> None: ...
    def paint(self) -> None: ...

Drawing Context

Surface Classes and Output Formats

Surface classes provide rendering targets for different output formats including in-memory images, PDF documents, SVG graphics, and PostScript files.

class Surface:
    def finish(self) -> None: ...
    def flush(self) -> None: ...
    def get_content(self) -> Content: ...

class ImageSurface(Surface):
    def __init__(self, format: Format, width: int, height: int) -> None: ...
    def write_to_png(self, filename: str) -> None: ...

class PDFSurface(Surface):
    def __init__(self, filename: str, width_in_points: float, height_in_points: float) -> None: ...

class SVGSurface(Surface):
    def __init__(self, filename: str, width_in_points: float, height_in_points: float) -> None: ...

Surfaces

Pattern Classes for Paint Sources

Pattern classes define paint sources for filling and stroking operations, including solid colors, gradients, and image-based patterns.

class Pattern:
    def get_extend(self) -> Extend: ...
    def set_extend(self, extend: Extend) -> None: ...

class SolidPattern(Pattern):
    def __init__(self, red: float, green: float, blue: float, alpha: float = 1.0) -> None: ...

class LinearGradient(Pattern):
    def __init__(self, x0: float, y0: float, x1: float, y1: float) -> None: ...
    def add_color_stop_rgb(self, offset: float, red: float, green: float, blue: float) -> None: ...

class RadialGradient(Pattern):
    def __init__(self, cx0: float, cy0: float, radius0: float, cx1: float, cy1: float, radius1: float) -> None: ...

Patterns

Geometry Classes for Shapes and Transformations

Classes for handling geometric data including vector paths, transformation matrices, rectangles, and regions.

class Path:
    def __iter__(self) -> Iterator[tuple[PathDataType, tuple[float, ...]]]: ...

class Matrix:
    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: ...
    def rotate(self, radians: float) -> None: ...
    def scale(self, sx: float, sy: float) -> None: ...
    def translate(self, tx: float, ty: float) -> None: ...

class Rectangle:
    def __init__(self, x: float, y: float, width: float, height: float) -> None: ...

Geometry

Text and Font Rendering

Comprehensive text rendering capabilities including font selection, text measurement, and advanced typography features.

class FontFace:
    def __init__(self) -> None: ...

class FontOptions:
    def __init__(self) -> None: ...
    def set_antialias(self, antialias: Antialias) -> None: ...
    def set_hint_style(self, hint_style: HintStyle) -> None: ...

class ScaledFont:
    def __init__(self, font_face: FontFace, font_matrix: Matrix, ctm: Matrix, options: FontOptions) -> None: ...
    def text_extents(self, text: str) -> TextExtents: ...

Text and Fonts

Constants and Enumerations

Comprehensive set of constants and enumeration types for controlling drawing parameters, format specifications, and rendering options.

class Format:
    INVALID: int
    ARGB32: int
    RGB24: int
    A8: int
    A1: int

class Antialias:
    DEFAULT: int
    NONE: int
    GRAY: int
    SUBPIXEL: int

# Version information
version: str
version_info: tuple[int, int, int]
CAIRO_VERSION: int
CAIRO_VERSION_STRING: str

Constants and Enums

Utility Functions

def cairo_version() -> int:
    """Return encoded version of underlying C cairo library."""

def cairo_version_string() -> str:
    """Return human-readable version string of C cairo library."""

def get_include() -> str:
    """Return path to directory containing C header files for extensions."""

Exception Handling

class Error(Exception):
    """Base class for all cairo-related exceptions"""
    pass

All Cairo operations that can fail will raise appropriate exceptions rather than return error codes, making error handling more Pythonic and robust.