Python interface for cairo graphics library providing 2D vector graphics, drawing operations, and rendering to multiple output formats
—
Cairo provides extensive enumeration types and constants that control drawing behavior, format specifications, and rendering options. These enumerations ensure type safety and provide meaningful names for Cairo's various modes and parameters.
class Antialias:
"""Antialiasing modes for rendering."""
DEFAULT: int = 0 # Use default antialiasing for subsystem and target device
NONE: int = 1 # Use bilevel alpha mask
GRAY: int = 2 # Perform single-color antialiasing using shades of gray
SUBPIXEL: int = 3 # Perform antialiasing by taking advantage of subpixel order
FAST: int = 4 # Hint to use speed over quality
GOOD: int = 5 # Hint to balance speed and quality
BEST: int = 6 # Hint to favor quality over speed
class Operator:
"""Compositing operators for blending operations."""
CLEAR: int = 0 # Clear destination layer
SOURCE: int = 1 # Replace destination with source
OVER: int = 2 # Draw source on top of destination (default)
IN: int = 3 # Draw source where there was destination content
OUT: int = 4 # Draw source where there was no destination content
ATOP: int = 5 # Draw source on top of destination content
DEST: int = 6 # Ignore source
DEST_OVER: int = 7 # Draw destination on top of source
DEST_IN: int = 8 # Leave destination only where source
DEST_OUT: int = 9 # Leave destination only where no source
DEST_ATOP: int = 10 # Leave destination on top of source content
XOR: int = 11 # Source and destination exclusive or
ADD: int = 12 # Source and destination are added
SATURATE: int = 13 # Like OVER but clamp to maximum
MULTIPLY: int = 14 # Source and destination multiplied
SCREEN: int = 15 # Source and destination complemented then multiplied
OVERLAY: int = 16 # Mix of MULTIPLY and SCREEN
DARKEN: int = 17 # Darker of source and destination
LIGHTEN: int = 18 # Lighter of source and destination
COLOR_DODGE: int = 19 # Brighten destination based on source
COLOR_BURN: int = 20 # Darken destination based on source
HARD_LIGHT: int = 21 # Mix of MULTIPLY and SCREEN based on source
SOFT_LIGHT: int = 22 # Softer version of HARD_LIGHT
DIFFERENCE: int = 23 # Absolute difference of source and destination
EXCLUSION: int = 24 # Similar to DIFFERENCE but lower contrast
HSL_HUE: int = 25 # Use hue of source with saturation and luminosity of destination
HSL_SATURATION: int = 26 # Use saturation of source
HSL_COLOR: int = 27 # Use hue and saturation of source
HSL_LUMINOSITY: int = 28 # Use luminosity of source
class FillRule:
"""Fill rules for determining interior of paths."""
WINDING: int = 0 # Non-zero winding rule (default)
EVEN_ODD: int = 1 # Even-odd rule
class LineCap:
"""Line cap styles for stroke endpoints."""
BUTT: int = 0 # Start/stop exactly at path endpoints (default)
ROUND: int = 1 # Circular arc with diameter equal to line width
SQUARE: int = 2 # Square end with width equal to line width
class LineJoin:
"""Line join styles for stroke corners."""
MITER: int = 0 # Sharp corner with miter limit (default)
ROUND: int = 1 # Circular arc joining path segments
BEVEL: int = 2 # Straight line connecting endpoints
class Filter:
"""Scaling filters for pattern sampling."""
FAST: int = 0 # Nearest-neighbor sampling
GOOD: int = 1 # Linear sampling (default)
BEST: int = 2 # Best available sampling algorithm
NEAREST: int = 3 # Nearest-neighbor sampling (same as FAST)
BILINEAR: int = 4 # Linear sampling (same as GOOD)
GAUSSIAN: int = 5 # Gaussian sampling
class Extend:
"""Pattern extend modes for areas outside pattern."""
NONE: int = 0 # Pixels outside pattern are transparent (default)
REPEAT: int = 1 # Pattern is tiled by repeating
REFLECT: int = 2 # Pattern is tiled by reflecting
PAD: int = 3 # Pattern is extended by repeating edge pixelsclass Format:
"""Pixel formats for image surfaces."""
INVALID: int = -1 # Invalid format
ARGB32: int = 0 # 32-bit ARGB (default for color images)
RGB24: int = 1 # 24-bit RGB
A8: int = 2 # 8-bit alpha channel only
A1: int = 3 # 1-bit alpha channel only
RGB16_565: int = 4 # 16-bit RGB in 5-6-5 format
RGB30: int = 5 # 30-bit RGB with 10 bits per component
RGB96F: int = 6 # 96-bit floating-point RGB (version 1.23+)
RGBA128F: int = 7 # 128-bit floating-point RGBA (version 1.23+)
@staticmethod
def stride_for_width(format: Format, width: int) -> int:
"""Calculate stride in bytes for given format and width."""
class Content:
"""Surface content types."""
COLOR: int = 0x1000 # Surface will hold color content only
ALPHA: int = 0x2000 # Surface will hold alpha content only
COLOR_ALPHA: int = 0x3000 # Surface will hold color and alpha contentclass FontSlant:
"""Font slant styles."""
NORMAL: int = 0 # Upright font (default)
ITALIC: int = 1 # Italic font
OBLIQUE: int = 2 # Oblique font
class FontWeight:
"""Font weight specifications."""
NORMAL: int = 0 # Normal weight (default)
BOLD: int = 1 # Bold weight
class HintStyle:
"""Font hinting styles."""
DEFAULT: int = 0 # Use default hint style for font backend and target
NONE: int = 1 # Do not hint outlines
SLIGHT: int = 2 # Hint outlines slightly for improved contrast
MEDIUM: int = 3 # Hint outlines with medium strength
FULL: int = 4 # Hint outlines to maximize contrast
class HintMetrics:
"""Font metrics hinting modes."""
DEFAULT: int = 0 # Hint metrics in default manner for target
OFF: int = 1 # Do not hint font metrics
ON: int = 2 # Hint font metrics
class SubpixelOrder:
"""Subpixel orders for LCD displays."""
DEFAULT: int = 0 # Use default subpixel order for target
RGB: int = 1 # Subpixels are arranged horizontally with red at left
BGR: int = 2 # Subpixels are arranged horizontally with blue at left
VRGB: int = 3 # Subpixels are arranged vertically with red at top
VBGR: int = 4 # Subpixels are arranged vertically with blue at top
class TextClusterFlags:
"""Text cluster direction flags."""
BACKWARD: int = 0x1 # Clusters represent text flowing backward
class ColorMode:
"""Color font rendering modes."""
DEFAULT: int = 0 # Use default color mode
NO_COLOR: int = 1 # Disable color font rendering
COLOR: int = 2 # Enable color font rendering
class Dither:
"""Dithering modes."""
NONE: int = 0 # No dithering
DEFAULT: int = 1 # Default dithering
FAST: int = 2 # Fast dithering
GOOD: int = 3 # Good quality dithering
BEST: int = 4 # Best quality ditheringclass PathDataType:
"""Path element types."""
MOVE_TO: int = 0 # Move to point
LINE_TO: int = 1 # Line to point
CURVE_TO: int = 2 # Cubic Bézier curve to point
CLOSE_PATH: int = 3 # Close current sub-path
class RegionOverlap:
"""Region overlap types."""
IN: int = 0 # Completely inside region
OUT: int = 1 # Completely outside region
PART: int = 2 # Partially overlaps regionclass PDFVersion:
"""PDF version constants."""
VERSION_1_4: int = 0 # PDF version 1.4
VERSION_1_5: int = 1 # PDF version 1.5
VERSION_1_6: int = 2 # PDF version 1.6 (version 1.23+)
VERSION_1_7: int = 3 # PDF version 1.7 (version 1.23+)
class PDFMetadata:
"""PDF metadata keys."""
TITLE: int = 0 # Document title
AUTHOR: int = 1 # Document author
SUBJECT: int = 2 # Document subject
KEYWORDS: int = 3 # Document keywords
CREATOR: int = 4 # Creating application
CREATE_DATE: int = 5 # Creation date
MOD_DATE: int = 6 # Modification date
class PDFOutlineFlags:
"""PDF outline item flags."""
OPEN: int = 1 # Outline item initially open
BOLD: int = 2 # Outline item text is bold
ITALIC: int = 4 # Outline item text is italic
class PSLevel:
"""PostScript language levels."""
LEVEL_2: int = 0 # PostScript Level 2
LEVEL_3: int = 1 # PostScript Level 3
class SVGVersion:
"""SVG version constants."""
VERSION_1_1: int = 0 # SVG version 1.1
VERSION_1_2: int = 1 # SVG version 1.2
class SVGUnit:
"""SVG unit types."""
USER: int = 0 # User units (default)
EM: int = 1 # Em units
EX: int = 2 # Ex units
PX: int = 3 # Pixel units
IN: int = 4 # Inch units
CM: int = 5 # Centimeter units
MM: int = 6 # Millimeter units
PT: int = 7 # Point units (1/72 inch)
PC: int = 8 # Pica units (12 points)
PERCENT: int = 9 # Percentage units
class ScriptMode:
"""Script recording modes."""
ASCII: int = 0 # Emit human-readable text
BINARY: int = 1 # Emit binary data
class SurfaceObserverMode:
"""Surface observer modes."""
NORMAL: int = 0 # Normal surface observation
RECORD_OPERATIONS: int = 1 # Record all drawing operations
class DeviceType:
"""Device types."""
DRM: int = 0 # DRM device
GL: int = 1 # OpenGL device
SCRIPT: int = 2 # Script recording device
XCB: int = 3 # XCB device
XLIB: int = 4 # Xlib device
XML: int = 5 # XML device
COGL: int = 6 # Cogl device
WIN32: int = 7 # Win32 device
INVALID: int = -1 # Invalid device type
class FontType:
"""Font face types."""
TOY: int = 0 # Toy font face
FT: int = 1 # FreeType font face
WIN32: int = 2 # Win32 font face
QUARTZ: int = 3 # Quartz font face
USER: int = 4 # User font face
DWRITE: int = 5 # DirectWrite font faceclass Status:
"""Cairo operation status codes."""
SUCCESS: int = 0 # No error has occurred
NO_MEMORY: int = 1 # Out of memory
INVALID_RESTORE: int = 2 # Context stack underflow
INVALID_POP_GROUP: int = 3 # No saved group to pop
NO_CURRENT_POINT: int = 4 # No current point defined
INVALID_MATRIX: int = 5 # Invalid matrix transformation
INVALID_STATUS: int = 6 # Invalid value for Status enum
NULL_POINTER: int = 7 # Null pointer
INVALID_STRING: int = 8 # Input string not valid UTF-8
INVALID_PATH_DATA: int = 9 # Input path data not valid
READ_ERROR: int = 10 # Error while reading from input stream
WRITE_ERROR: int = 11 # Error while writing to output stream
SURFACE_FINISHED: int = 12 # Target surface finished
SURFACE_TYPE_MISMATCH: int = 13 # Surface type not appropriate
PATTERN_TYPE_MISMATCH: int = 14 # Pattern type not appropriate
INVALID_CONTENT: int = 15 # Invalid value for Content enum
INVALID_FORMAT: int = 16 # Invalid value for Format enum
INVALID_VISUAL: int = 17 # Invalid value for Visual
FILE_NOT_FOUND: int = 18 # File not found
INVALID_DASH: int = 19 # Invalid value for dash setting
INVALID_DSC_COMMENT: int = 20 # Invalid DSC comment
INVALID_INDEX: int = 21 # Invalid index passed
CLIP_NOT_REPRESENTABLE: int = 22 # Clip region not representable
TEMP_FILE_ERROR: int = 23 # Error creating temporary file
INVALID_STRIDE: int = 24 # Invalid value for stride
FONT_TYPE_MISMATCH: int = 25 # Font type not appropriate
USER_FONT_IMMUTABLE: int = 26 # User font is immutable
USER_FONT_ERROR: int = 27 # Error in user font
NEGATIVE_COUNT: int = 28 # Negative number used where not allowed
INVALID_CLUSTERS: int = 29 # Invalid clusters
INVALID_SLANT: int = 30 # Invalid value for FontSlant enum
INVALID_WEIGHT: int = 31 # Invalid value for FontWeight enum
INVALID_SIZE: int = 32 # Invalid value for size
USER_FONT_NOT_IMPLEMENTED: int = 33 # User font method not implemented
DEVICE_TYPE_MISMATCH: int = 34 # Device type not appropriate
DEVICE_ERROR: int = 35 # Error in device
INVALID_MESH_CONSTRUCTION: int = 36 # Invalid mesh construction
DEVICE_FINISHED: int = 37 # Device finished
JBIG2_GLOBAL_MISSING: int = 38 # JBIG2 global segment missing
PNG_ERROR: int = 39 # PNG format error (version 1.18+)
FREETYPE_ERROR: int = 40 # FreeType error (version 1.18+)
WIN32_GDI_ERROR: int = 41 # Win32 GDI error (version 1.18+)
TAG_ERROR: int = 42 # PDF tagging error (version 1.18+)
DWRITE_ERROR: int = 43 # DirectWrite error (version 1.23+)
SVG_FONT_ERROR: int = 44 # SVG font error (version 1.25+)# Version information
version: str # Pycairo version string
version_info: tuple[int, int, int] # Pycairo version tuple
CAIRO_VERSION: int # Cairo library version (encoded)
CAIRO_VERSION_STRING: str # Cairo library version string
CAIRO_VERSION_MAJOR: int # Cairo major version
CAIRO_VERSION_MINOR: int # Cairo minor version
CAIRO_VERSION_MICRO: int # Cairo micro version
# Feature availability flags
HAS_ATSUI_FONT: bool # ATSUI font backend available
HAS_FT_FONT: bool # FreeType font backend available
HAS_GLITZ_SURFACE: bool # Glitz surface backend available
HAS_IMAGE_SURFACE: bool # Image surface backend available
HAS_MIME_SURFACE: bool # MIME surface support available
HAS_PDF_SURFACE: bool # PDF surface backend available
HAS_PNG_FUNCTIONS: bool # PNG read/write functions available
HAS_PS_SURFACE: bool # PostScript surface backend available
HAS_QUARTZ_SURFACE: bool # Quartz surface backend available
HAS_RECORDING_SURFACE: bool # Recording surface backend available
HAS_SCRIPT_SURFACE: bool # Script surface backend available
HAS_SVG_SURFACE: bool # SVG surface backend available
HAS_TEE_SURFACE: bool # Tee surface backend available
HAS_USER_FONT: bool # User font backend available
HAS_WIN32_FONT: bool # Win32 font backend available
HAS_WIN32_SURFACE: bool # Win32 surface backend available
HAS_XCB_SURFACE: bool # XCB surface backend available
HAS_XLIB_SURFACE: bool # Xlib surface backend available
HAS_DWRITE_FONT: bool # DirectWrite font backend available
# Special constants
PDF_OUTLINE_ROOT: int # Root outline item ID for PDF
COLOR_PALETTE_DEFAULT: int # Default color palette index
# MIME type constants
MIME_TYPE_JPEG: str # JPEG MIME type
MIME_TYPE_PNG: str # PNG MIME type
MIME_TYPE_URI: str # URI MIME type
MIME_TYPE_UNIQUE_ID: str # Unique ID MIME type
MIME_TYPE_CCITT_FAX: str # CCITT FAX MIME type
MIME_TYPE_CCITT_FAX_PARAMS: str # CCITT FAX parameters MIME type
MIME_TYPE_EPS: str # EPS MIME type
MIME_TYPE_EPS_PARAMS: str # EPS parameters MIME type
# Tag constants
TAG_DEST: str # Destination tag
TAG_LINK: str # Link tag
TAG_CONTENT: str # Content tag
TAG_CONTENT_REF: str # Content reference tag
# MIME type constants
MIME_TYPE_JPEG: str = "image/jpeg" # JPEG format
MIME_TYPE_PNG: str = "image/png" # PNG format
MIME_TYPE_JP2: str = "image/jp2" # JPEG 2000 format
MIME_TYPE_URI: str = "text/x-uri" # URI for image file
MIME_TYPE_UNIQUE_ID: str = "application/x-cairo.uuid" # Unique surface identifier
MIME_TYPE_CCITT_FAX: str = "image/g3fax" # CCITT fax encoding
MIME_TYPE_CCITT_FAX_PARAMS: str = "application/x-cairo.ccitt.params" # CCITT fax parameters
MIME_TYPE_EPS: str = "application/postscript" # Encapsulated PostScript
MIME_TYPE_EPS_PARAMS: str = "application/x-cairo.eps.params" # EPS parameters
MIME_TYPE_JBIG2: str = "application/x-cairo.jbig2" # JBIG2 format
MIME_TYPE_JBIG2_GLOBAL: str = "application/x-cairo.jbig2-global" # JBIG2 global segment
MIME_TYPE_JBIG2_GLOBAL_ID: str = "application/x-cairo.jbig2-global-id" # JBIG2 identifier
# Tag constants
TAG_DEST: str = "cairo.dest" # Hyperlink destination tag
TAG_LINK: str = "Link" # Hyperlink tag
TAG_CONTENT: str = "cairo.content" # Content tag
TAG_CONTENT_REF: str = "cairo.content_ref" # Content reference tag
# C API interface
CAPI: Any # C API interface objectimport cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)
# Using operator enums
operators = [
cairo.OPERATOR_OVER,
cairo.OPERATOR_MULTIPLY,
cairo.OPERATOR_SCREEN,
cairo.OPERATOR_OVERLAY,
cairo.OPERATOR_DARKEN,
cairo.OPERATOR_LIGHTEN
]
# Draw rectangles with different operators
ctx.set_source_rgb(0.8, 0.2, 0.2)
ctx.rectangle(50, 50, 100, 80)
ctx.fill()
for i, op in enumerate(operators):
ctx.set_operator(op)
ctx.set_source_rgba(0.2, 0.2, 0.8, 0.7)
ctx.rectangle(100 + i * 30, 70, 60, 60)
ctx.fill()
# Reset operator
ctx.set_operator(cairo.OPERATOR_OVER)
surface.write_to_png("operators.png")import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
# Line cap styles
line_caps = [
(cairo.LINE_CAP_BUTT, "BUTT"),
(cairo.LINE_CAP_ROUND, "ROUND"),
(cairo.LINE_CAP_SQUARE, "SQUARE")
]
ctx.set_source_rgb(0, 0, 0)
ctx.set_line_width(20)
y = 50
for cap, name in line_caps:
ctx.set_line_cap(cap)
ctx.move_to(50, y)
ctx.line_to(200, y)
ctx.stroke()
# Label
ctx.save()
ctx.set_line_width(1)
ctx.select_font_face("Arial")
ctx.set_font_size(12)
ctx.move_to(220, y + 5)
ctx.show_text(name)
ctx.restore()
y += 40
# Line join styles
line_joins = [
(cairo.LINE_JOIN_MITER, "MITER"),
(cairo.LINE_JOIN_ROUND, "ROUND"),
(cairo.LINE_JOIN_BEVEL, "BEVEL")
]
x = 50
for join, name in line_joins:
ctx.set_line_join(join)
ctx.set_line_width(15)
# Draw angle
ctx.move_to(x, 200)
ctx.line_to(x + 30, 160)
ctx.line_to(x + 60, 200)
ctx.stroke()
# Label
ctx.save()
ctx.set_line_width(1)
ctx.move_to(x, 220)
ctx.show_text(name)
ctx.restore()
x += 100
surface.write_to_png("line_styles.png")import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 300)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
# Create self-intersecting path
def create_star_path(ctx, x, y, size):
ctx.move_to(x, y - size)
ctx.line_to(x + size * 0.3, y + size * 0.8)
ctx.line_to(x - size * 0.8, y - size * 0.3)
ctx.line_to(x + size * 0.8, y - size * 0.3)
ctx.line_to(x - size * 0.3, y + size * 0.8)
ctx.close_path()
# Even-odd fill rule
ctx.save()
ctx.translate(120, 150)
create_star_path(ctx, 0, 0, 80)
ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
ctx.set_source_rgb(0.8, 0.2, 0.2)
ctx.fill()
ctx.restore()
# Winding fill rule
ctx.save()
ctx.translate(350, 150)
create_star_path(ctx, 0, 0, 80)
ctx.set_fill_rule(cairo.FILL_RULE_WINDING)
ctx.set_source_rgb(0.2, 0.2, 0.8)
ctx.fill()
ctx.restore()
# Labels
ctx.set_source_rgb(0, 0, 0)
ctx.select_font_face("Arial")
ctx.set_font_size(14)
ctx.move_to(60, 260)
ctx.show_text("EVEN_ODD")
ctx.move_to(300, 260)
ctx.show_text("WINDING")
surface.write_to_png("fill_rules.png")import cairo
# Check available features
print("Available Cairo features:")
features = [
("Image Surface", cairo.HAS_IMAGE_SURFACE),
("PDF Surface", cairo.HAS_PDF_SURFACE),
("SVG Surface", cairo.HAS_SVG_SURFACE),
("PS Surface", cairo.HAS_PS_SURFACE),
("PNG Functions", cairo.HAS_PNG_FUNCTIONS),
("FreeType Fonts", cairo.HAS_FT_FONT),
("Win32 Fonts", cairo.HAS_WIN32_FONT),
("Win32 Surface", cairo.HAS_WIN32_SURFACE),
("User Fonts", cairo.HAS_USER_FONT),
("Script Surface", cairo.HAS_SCRIPT_SURFACE),
("Recording Surface", cairo.HAS_RECORDING_SURFACE),
("Tee Surface", cairo.HAS_TEE_SURFACE),
("DirectWrite Fonts", cairo.HAS_DWRITE_FONT)
]
for name, available in features:
status = "✓" if available else "✗"
print(f" {status} {name}")
# Version information
print(f"\nVersion information:")
print(f" Pycairo version: {cairo.version}")
print(f" Pycairo version info: {cairo.version_info}")
print(f" Cairo version: {cairo.CAIRO_VERSION_STRING}")
print(f" Cairo version components: {cairo.CAIRO_VERSION_MAJOR}.{cairo.CAIRO_VERSION_MINOR}.{cairo.CAIRO_VERSION_MICRO}")
# Format information
formats = [
("ARGB32", cairo.FORMAT_ARGB32),
("RGB24", cairo.FORMAT_RGB24),
("A8", cairo.FORMAT_A8),
("A1", cairo.FORMAT_A1),
("RGB16_565", cairo.FORMAT_RGB16_565),
("RGB30", cairo.FORMAT_RGB30)
]
print(f"\nSupported formats:")
for name, format_val in formats:
# Calculate stride for 100px width
stride = cairo.ImageSurface.format_stride_for_width(format_val, 100)
print(f" {name}: stride for 100px = {stride} bytes")
# Create surfaces with different formats
surface_argb32 = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
surface_rgb24 = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 100)
surface_a8 = cairo.ImageSurface(cairo.FORMAT_A8, 100, 100)
print(f"\nSurface properties:")
print(f" ARGB32 surface: {surface_argb32.get_width()}x{surface_argb32.get_height()}, stride={surface_argb32.get_stride()}")
print(f" RGB24 surface: {surface_rgb24.get_width()}x{surface_rgb24.get_height()}, stride={surface_rgb24.get_stride()}")
print(f" A8 surface: {surface_a8.get_width()}x{surface_a8.get_height()}, stride={surface_a8.get_stride()}")import cairo
try:
# Create surface
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)
# Try to create an invalid matrix
matrix = cairo.Matrix(1, 0, 0, 0, 0, 0) # Singular matrix
try:
matrix.invert()
print("Matrix inversion succeeded")
except cairo.Error as e:
print(f"Matrix inversion failed: {e}")
# Try to use invalid path data
try:
# This should work fine
ctx.move_to(50, 50)
ctx.line_to(100, 100)
path = ctx.copy_path()
# Use the path
ctx.new_path()
ctx.append_path(path)
ctx.stroke()
print("Path operations succeeded")
except cairo.Error as e:
print(f"Path operation failed: {e}")
# Try to read a non-existent PNG
try:
invalid_surface = cairo.ImageSurface.create_from_png("nonexistent.png")
print("PNG loading succeeded")
except cairo.Error as e:
print(f"PNG loading failed: {e}")
surface.write_to_png("error_handling.png")
print("Surface write succeeded")
except cairo.Error as e:
print(f"Cairo error: {e}")
except Exception as e:
print(f"Other error: {e}")import cairo
# Using MIME type constants
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
ctx = cairo.Context(surface)
# Draw something
ctx.set_source_rgb(0.8, 0.2, 0.2)
ctx.rectangle(50, 50, 100, 100)
ctx.fill()
# Attach MIME data (conceptual example)
# In practice, you would have actual image data
example_data = b"example image data"
surface.set_mime_data(cairo.MIME_TYPE_PNG, example_data)
# Check if MIME type is supported
png_supported = surface.supports_mime_type(cairo.MIME_TYPE_PNG)
jpeg_supported = surface.supports_mime_type(cairo.MIME_TYPE_JPEG)
print(f"PNG MIME support: {png_supported}")
print(f"JPEG MIME support: {jpeg_supported}")
# Using tag constants in PDF (conceptual)
if cairo.HAS_PDF_SURFACE:
pdf_surface = cairo.PDFSurface("tagged.pdf", 400, 300)
pdf_ctx = cairo.Context(pdf_surface)
# These would be used with PDF tagging operations
print(f"Available tags: {cairo.TAG_DEST}, {cairo.TAG_LINK}, {cairo.TAG_CONTENT}")
pdf_surface.finish()
# Using special constants
print(f"PDF outline root: {cairo.PDF_OUTLINE_ROOT}")
print(f"Default color palette: {cairo.COLOR_PALETTE_DEFAULT}")
surface.write_to_png("constants_demo.png")Install with Tessl CLI
npx tessl i tessl/pypi-pycairo