### Basic Cairo Drawing with cairocffi Source: https://doc.courtbouillon.org/cairocffi/stable/overview.html Demonstrates creating an image surface, a drawing context, setting colors, drawing text, and saving the output as a PNG file. This is a fundamental example for getting started with cairocffi. ```python import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200) context = cairo.Context(surface) with context: context.set_source_rgb(1, 1, 1) # White context.paint() # Restore the default source which is black. context.move_to(90, 140) context.rotate(-0.5) context.set_font_size(20) context.show_text('Hi from cairo!') surface.write_to_png('example.png') ``` -------------------------------- ### Install cairocffi with XCB support Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Install xcffib before cairocffi to enable XCB support. ```bash pip install xcffib pip install cairocffi ``` -------------------------------- ### Pango Integration Example Source: https://doc.courtbouillon.org/cairocffi An example demonstrating the usage of Pango through CFFI with cairocffi. This showcases how to combine these libraries for text rendering. ```python Example: using Pango through CFFI with cairocffi ``` -------------------------------- ### Install cairocffi via pip Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Standard installation command for the library. ```bash pip install cairocffi ``` -------------------------------- ### Install cairocffi Source: https://doc.courtbouillon.org/cairocffi/stable/overview.html Commands to install the library via pip, including optional XCB support. ```bash pip install cairocffi ``` ```bash pip install xcffib pip install cairocffi ``` -------------------------------- ### Initialize surface and context Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Basic setup for creating an image surface and a drawing context. ```python import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200) context = cairo.Context(surface) with context: ``` -------------------------------- ### Install as Pycairo Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Use install_as_pycairo to force existing code to use cairocffi instead of Pycairo. ```python import cairocffi cairocffi.install_as_pycairo() import cairo assert cairo is cairocffi ``` -------------------------------- ### cairocffi Installation and Versioning Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Functions to install cairocffi as a replacement for pycairo and to retrieve Cairo version information. ```APIDOC ## cairocffi.install_as_pycairo() ### Description Installs cairocffi such that `import cairo` will import this library. The API is designed to be compatible with pycairo. ### Method N/A (Function call) ### Endpoint N/A ### Parameters None ### Request Example ```python import cairocffi cairocffi.install_as_pycairo() ``` ### Response N/A ``` ```APIDOC ## cairocffi.cairo_version() ### Description Returns the Cairo version number as a single integer. For example, `1.12.8` is returned as `11208`. Major, minor, and micro versions are weighted by 10000, 100, and 1 respectively. This can be used to check for method availability in older Cairo versions. ### Method N/A (Function call) ### Endpoint N/A ### Parameters None ### Request Example ```python from cairocffi import cairo_version if cairo_version() >= 11000: print("Cairo version 1.10 or higher detected.") ``` ### Response - **integer** - The Cairo version number as an integer. ``` ```APIDOC ## cairocffi.cairo_version_string() ### Description Returns the Cairo version number as a string, for example, `"1.12.8"`. ### Method N/A (Function call) ### Endpoint N/A ### Parameters None ### Request Example ```python from cairocffi import cairo_version_string print(f"Cairo version: {cairo_version_string()}") ``` ### Response - **string** - The Cairo version number as a string. ``` -------------------------------- ### Move to Point Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Starts a new sub-path at the specified point. ```APIDOC ## POST move_to(x, y) ### Description Begin a new sub-path. After this call the current point will be `(x, y)`. ### Parameters #### Path Parameters - **x** (float) - X coordinate of the point. - **y** (float) - Y coordinate of the point. ### Method POST ### Endpoint /move_to ``` -------------------------------- ### Display version information Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Interactive shell examples for checking cairo, pycairo, and cairocffi versions. ```python >>> print("The cairo version is %s, meaning %s." ... % (cairocffi.cairo_version(), cairocffi.cairo_version_string())) The cairo version is 11402, meaning 1.14.02. >>> print("The latest pycairo version this cairocffi version is compatible with is %s." ... % cairo.version) The latest pycairo version this cairocffi version is compatible with is 1.10.0. >>> print("The cairocffi version is %s." % cairo.VERSION) The cairocffi version is 0.7.2 ``` -------------------------------- ### Using Pango with CairoFFI via CFFI Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/cffi_api.rst.txt This example demonstrates using Pango's C API through CFFI, integrating with CairoFFI by passing `Context._pointer` directly to CFFI functions expecting `cairo_t *`. C definitions are sourced from Pango and GLib documentation. ```python from cffi import FFI from cairocffi import Context, Matrix clib = FFI() # C definitions copied from Pango and GLib documentation clib.cdef(r''' typedef struct _PangoLayout PangoLayout; typedef struct _PangoFont PangoFont; typedef struct _PangoFontDescription PangoFontDescription; void pango_layout_set_text (PangoLayout *layout, const char *text, int length); void pango_layout_set_font_description (PangoLayout *layout, PangoFontDescription *desc); void pango_layout_get_size (PangoLayout *layout, int *w, int *h); void pango_cairo_update_layout (cairo_t *cr, PangoLayout *layout); void pango_cairo_show_layout (cairo_t *cr, PangoLayout *layout); PangoLayout *pango_layout_new (PangoContext *context); PangoContext *pango_layout_get_context (PangoLayout *layout); void pango_layout_unref (PangoLayout *layout); PangoFontDescription *pango_font_description_new (void); void pango_font_description_set_family (PangoFontDescription *desc, const char *family); void pango_font_description_set_size (PangoFontDescription *desc, int size); void pango_font_description_free (PangoFontDescription *desc); PangoContext *pango_context_new (void); void pango_context_free (PangoContext *context); cairo_status_t cairo_status_t (void); typedef enum { CAIRO_STATUS_SUCCESS = 0, CAIRO_STATUS_NO_MEMORY = 1, CAIRO_STATUS_INVALID_RESTORE = 2, CAIRO_STATUS_INVALID_POP = 3, CAIRO_STATUS_END_OF_FILE = 4, CAIRO_STATUS_WRITE_ERROR = 5, CAIRO_STATUS_READ_ERROR = 6, CAIRO_STATUS_INVALID_INDEX = 7, CAIRO_STATUS_ প্যারামিটার_ERROR = 8, CAIRO_STATUS_INVALID_STRING = 9, CAIRO_STATUS_NULL_POINTER = 10, CAIRO_STATUS_INVALID_GROUP = 11, CAIRO_STATUS_CLIP_NOT_REPLACEABLE = 12, CAIRO_STATUS_DEVICE_ERROR = 13, CAIRO_STATUS_DEVICE_FINISHED = 14, CAIRO_STATUS_INVALID_FORMAT = 15, CAIRO_STATUS_INVALID_VISUAL = 16, CAIRO_STATUS_FILE_NOT_FOUND = 17, CAIRO_STATUS_TAG_ERROR = 18, CAIRO_STATUS_ERROR_UNKNOWN = 19 } cairo_status_t; ''' ) # Load libcairo and libpangocairo # On Linux, this is usually libcairo-2.so and libpangocairo-1.0.so # On macOS, it's libcairo.2.dylib and libpangocairo-1.0.dylib # On Windows, it's cairo.dll and pango-1.0.dll # You might need to adjust these paths based on your system. cairo = clib.dlopen('libcairo-2.so') pangocairo = clib.dlopen('libpangocairo-1.0.so') # Create a Cairo context (e.g., for an image surface) width, height = 256, 256 surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, width, height) cr = Context(surface) # Create a Pango layout layout = clib.pango_layout_new(clib.pango_layout_get_context(None)) # Set text and font description text = "Hello, Pango!" font_desc = clib.pango_font_description_new() clib.pango_font_description_set_family(font_desc, "Sans") clib.pango_font_description_set_size(font_desc, 24 * 512) # Pango uses 1/24th of a point clib.pango_layout_set_font_description(layout, font_desc) clib.pango_layout_set_text(layout, text, -1) # Update the Pango layout for the Cairo context clib.pango_cairo_update_layout(cr._pointer, layout) # Show the Pango layout on the Cairo surface clib.pango_cairo_show_layout(cr._pointer, layout) # Get layout dimensions and draw a rectangle around it width_p, height_p = ffi.new("int *", 0), ffi.new("int *", 0) clib.pango_layout_get_size(layout, width_p, height_p) cr.rectangle(0, 0, width_p[0] / 512.0, height_p[0] / 512.0) # Convert from Pango units to points cr.set_line_width(1) cr.set_source_rgb(0.5, 0.5, 0.5) # Gray border cr.stroke() # Clean up Pango objects clib.pango_layout_unref(layout) clib.pango_font_description_free(font_desc) # Save the image surface.write_to_png("pango_example.png") ``` -------------------------------- ### Get Source Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current source pattern. ```APIDOC ## GET get_source() ### Description Return this context’s source. ### Returns An instance of `Pattern` or one of its sub-classes, a new Python object referencing the existing cairo pattern. ### Method GET ### Endpoint /get_source ``` -------------------------------- ### Handle library not found error Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Example of the exception raised if the cairo shared library cannot be located. ```text OSError: library not found: 'cairo' ``` -------------------------------- ### Meta Functions and Exceptions Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/api.rst.txt Provides access to installation status, Cairo version information, and error handling. ```APIDOC ## Meta Functions and Exceptions ### Description Provides functions to check installation status, retrieve Cairo version information, and handle Cairo-specific errors. ### Functions - **install_as_pycairo()**: Installs cairocffi as a replacement for Pycairo. - **cairo_version()**: Returns the Cairo version as an integer. - **cairo_version_string()**: Returns the Cairo version as a string. ### Exceptions - **CairoError**: Base exception for Cairo-related errors. - **Error**: Alias for `CairoError` for compatibility with Pycairo. ``` -------------------------------- ### Get Target Surface Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current target surface. ```APIDOC ## GET get_target() ### Description Return this context’s target surface. ### Returns An instance of `Surface` or one of its sub-classes, a new Python object referencing the existing cairo surface. ### Method GET ### Endpoint /get_target ``` -------------------------------- ### Meta Functions and Classes Source: https://doc.courtbouillon.org/cairocffi Provides access to cairo version information, error handling, and installation utilities. ```APIDOC ## Meta Functions and Classes ### Description Provides access to cairo version information, error handling, and installation utilities. ### Functions - `install_as_pycairo()`: Installs cairocffi as a replacement for pycairo. - `cairo_version()`: Returns the cairo version as an integer. - `cairo_version_string()`: Returns the cairo version as a string. ### Exceptions - `CairoError`: Base exception for cairocffi errors. - `Error`: Alias for `CairoError`. ``` -------------------------------- ### Path Management Methods Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for clearing paths and starting new sub-paths. ```APIDOC ## new_path() ### Description Clears the current path. After this call there will be no path and no current point. ## new_sub_path() ### Description Begin a new sub-path. Note that the existing path is not affected. After this call there will be no current point. ``` -------------------------------- ### CairoCFFI Meta Functions Source: https://doc.courtbouillon.org/cairocffi/stable/xcb.html Functions for managing Cairo installation and version information. ```APIDOC ## CairoCFFI Meta Functions ### Description Provides functions to install Cairo as pycairo, get Cairo version information, and access Cairo-related errors. ### Functions #### `install_as_pycairo()` Installs Cairo as if it were pycairo. #### `cairo_version()` Returns the Cairo version as an integer. #### `cairo_version_string()` Returns the Cairo version as a string. #### `CairoError` Base exception for Cairo-related errors. #### `Error` Alias for `CairoError`. ``` -------------------------------- ### Check Cairo Version for Feature Availability Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Use `cairo_version()` to check the Cairo version and conditionally use features. This example shows how to check if `set_mime_data` is available. ```python if cairo_version() >= 11000: surface.set_mime_data('image/jpeg', jpeg_bytes) ``` -------------------------------- ### Context State Management with Context Manager Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Demonstrates the recommended usage of save and restore using a with statement compared to manual calls. ```python with context: do_something(context) ``` ```python context.save() try: do_something(context) finally: context.restore() ``` -------------------------------- ### Configure FontOptions Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Demonstrates creating a FontOptions instance and setting antialiasing preferences. ```python options = FontOptions() options.set_antialias(cairocffi.ANTIALIAS_BEST) assert FontOptions(antialias=cairocffi.ANTIALIAS_BEST) == options ``` -------------------------------- ### Get Tolerance Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current tolerance value. ```APIDOC ## GET get_tolerance() ### Description Return the current tolerance as a float. ### Method GET ### Endpoint /get_tolerance ``` -------------------------------- ### Get Glyph Extents Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Calculates the extents for a list of glyphs. ```APIDOC ## GET glyph_extents(glyphs) ### Description Returns the extents for a list of glyphs. The extents describe a user-space rectangle that encloses the “inked” portion of the glyphs, (as it would be drawn by `show_glyphs()`). Additionally, the `x_advance` and `y_advance` values indicate the amount by which the current point would be advanced by `show_glyphs()`. ### Parameters #### Path Parameters - **glyphs** (list) - A list of glyphs. See `show_text_glyphs()` for the data structure. ### Returns A `(x_bearing, y_bearing, width, height, x_advance, y_advance)` tuple of floats. See `text_extents()` for details. ### Method GET ### Endpoint /glyph_extents ``` -------------------------------- ### tag_begin() Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Marks the beginning of a tagged structure. ```APIDOC ## tag_begin(_tag_name_, _attributes =None_) ### Description Marks the beginning of a structure identified by `tag_name`. Must be paired with a call to `tag_end()` with the same `tag_name`. The `attributes` string is a space-separated sequence of key-value pairs (e.g., "key1=value1 key2=value2"). Values can be boolean (true/false, 1/0), integer, float, string, or array. String values must be enclosed in single quotes (`'`) and internal single quotes or backslashes must be escaped with a backslash. ### Method (Implicitly a method of a cairo context object) ### Endpoint (N/A - Function call) ### Parameters - **_tag_name_** (string) - The name of the tag marking the beginning of the structure. - **_attributes** (string, optional) - A string containing key-value attributes for the tag. ``` -------------------------------- ### Get Scaled Font Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current scaled font. ```APIDOC ## GET get_scaled_font() ### Description Return the current scaled font. ### Returns A new `ScaledFont` object, wrapping an existing cairo object. ### Method GET ### Endpoint /get_scaled_font ``` -------------------------------- ### Get Composition Operator Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current composition operator. ```APIDOC ## GET get_operator() ### Description Return the current Compositiong operator string. ### Method GET ### Endpoint /get_operator ``` -------------------------------- ### Initialize an ImageSurface Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/api.rst.txt Demonstrates the usage of cairocffi constants when initializing an ImageSurface. ```python surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) ``` -------------------------------- ### Get Miter Limit Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current miter limit. ```APIDOC ## GET get_miter_limit() ### Description Return the current miter limit as a float. ### Method GET ### Endpoint /get_miter_limit ``` -------------------------------- ### Get Line Width Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current line width. ```APIDOC ## GET get_line_width() ### Description Return the current line width as a float. ### Method GET ### Endpoint /get_line_width ``` -------------------------------- ### Get Transformation Matrix Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves a copy of the current transformation matrix. ```APIDOC ## GET get_matrix() ### Description Return a copy of the current transformation matrix (CTM). ### Method GET ### Endpoint /get_matrix ``` -------------------------------- ### PSSurface Constructor Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Creates a PostScript surface of the specified size in PostScript points to be written to target. The target can be a filename, a file object, or None. The size of individual pages can vary. ```APIDOC ## PSSurface Constructor ### Description Creates a PostScript surface of the specified size in PostScript points to be written to `target`. ### Parameters - **target** - A filename, a binary mode file object with a `write` method, or `None`. - **width_in_points** (float) - Width of the surface, in points (1 point == 1/72.0 inch) - **height_in_points** (float) - Height of the surface, in points (1 point == 1/72.0 inch) ### Request Example ```python from cairoffi import PSSurface surface = PSSurface(None, 600, 800) ``` ``` -------------------------------- ### Win32PrintingSurface Class Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Creates a cairo surface that targets a Windows printing DC. ```APIDOC ## Win32PrintingSurface ### Description Creates a cairo surface that targets the given DC, intended for printing operations. ### Constructor `cairocffi.Win32PrintingSurface(hdc)` ### Parameters - **hdc** (int) - Required - The DC to create a surface for, interpreted as a pointer. ``` -------------------------------- ### Get Line Join Style Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current line join style. ```APIDOC ## GET get_line_join() ### Description Return the current Line join style string. ### Method GET ### Endpoint /get_line_join ``` -------------------------------- ### Get Line Cap Style Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Retrieves the current line cap style. ```APIDOC ## GET get_line_cap() ### Description Return the current Line cap style string. ### Method GET ### Endpoint /get_line_cap ``` -------------------------------- ### ImageSurface Creation Comparison Source: https://doc.courtbouillon.org/cairocffi/stable/changelog.html Compares the syntax for creating an ImageSurface before and after cairocffi version 0.4. The latter uses constants for format specification. ```python # Before cairocffi 0.4: surface = cairocffi.ImageSurface('ARGB32', 300, 400) ``` ```python # All cairocffi versions: surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) ``` -------------------------------- ### Import all from cairocffi Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Alternative method to shadow Pycairo by importing all symbols into the namespace. ```python from cairocffi import * ``` -------------------------------- ### Import cairocffi as cairo Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/overview.rst.txt Standard import pattern to allow coexistence with Pycairo. ```python import cairocffi as cairo ``` -------------------------------- ### Rectangle Path Construction Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Shows the logical implementation of the rectangle method using basic path commands. ```python context.move_to(x, y) context.rel_line_to(width, 0) context.rel_line_to(0, height) context.rel_line_to(-width, 0) context.close_path() ``` -------------------------------- ### Show Page Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Emits and clears the current page for backends that support multiple pages. Use `copy_page()` if you don’t want to clear the page. ```APIDOC ## POST /show_page ### Description Emits and clears the current page for backends that support multiple pages. Use `copy_page()` if you don’t want to clear the page. ### Method POST ### Endpoint `/show_page` ``` -------------------------------- ### Wrapper Classes Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/cffi_api.rst.txt Overview of wrapper classes and their underlying C pointers. ```APIDOC ## Wrapper Classes ### Description Cairocffi provides Pythonic wrappers for cairo objects. Each wrapper exposes an underlying C pointer. ### Attributes - **Surface._pointer** (cdata) - The underlying `cairo_surface_t *` pointer. - **Pattern._pointer** (cdata) - The underlying `cairo_pattern_t *` pointer. - **FontFace._pointer** (cdata) - The underlying `cairo_font_face_t *` pointer. - **ScaledFont._pointer** (cdata) - The underlying `cairo_scaled_font_t *` pointer. - **FontOptions._pointer** (cdata) - The underlying `cairo_scaled_font_t *` pointer. - **Matrix._pointer** (cdata) - The underlying `cairo_matrix_t *` pointer. - **Context._pointer** (cdata) - The underlying `cairo_t *` pointer. ``` -------------------------------- ### Image Loading and XCB Surfaces Source: https://doc.courtbouillon.org/cairocffi/stable/index.html Details on image loading errors and using XCB surfaces with xcffib. ```APIDOC ## Image Loading and XCB Surfaces ### Description This section details specific functionalities related to image loading and the integration with XCB surfaces using the `xcffib` library. ### Image Loading Errors - **`ImageLoadingError`**: A custom exception class raised when there are issues during image loading. ### XCB Surface Usage - **Using XCB surfaces with `xcffib`**: Documentation and examples for utilizing XCB (X protocol C-binding) surfaces with the `xcffib` library, which provides Python bindings for XCB. ### Decode to Image Surface - **`decode_to_image_surface()`**: A function that decodes various image formats into a cairo image surface. This function likely handles different image types and potential loading errors. ``` -------------------------------- ### Get Inverse Matrix Source: https://doc.courtbouillon.org/cairocffi/stable/api.html The `inverted()` method returns a new Matrix object that is the inverse of the current matrix, without modifying the original. It will fail for degenerate matrices. ```python matrix.inverted() ``` -------------------------------- ### Surface API Source: https://doc.courtbouillon.org/cairocffi Reference for the `Surface` class and its various implementations (ImageSurface, PDFSurface, PSSurface, SVGSurface, RecordingSurface, Win32PrintingSurface). ```APIDOC ## Surface API ### Description Reference for the `Surface` class and its various implementations (ImageSurface, PDFSurface, PSSurface, SVGSurface, RecordingSurface, Win32PrintingSurface). ### `Surface` Class #### Methods - `copy_page()`: Copies the current page to the surface. - `create_for_rectangle(x0, y0, x1, y1)`: Creates a new surface for a given rectangle. - `create_similar(content, width, height)`: Creates a new surface similar to the current one. - `create_similar_image(format, width, height)`: Creates a new image surface similar to the current one. - `finish()`: Finishes the surface and releases resources. - `flush()`: Flushes any pending drawing operations. - `get_content()`: Returns the content type of the surface. - `get_device_offset()`: Gets the device offset. - `get_device_scale()`: Gets the device scale. - `get_fallback_resolution(width, height)`: Gets the fallback resolution. - `get_font_options()`: Gets the font options. - `get_mime_data(mime_type)`: Gets MIME data from the surface. - `has_show_text_glyphs()`: Checks if the surface supports showing text glyphs. - `mark_dirty()`: Marks the entire surface as dirty. - `mark_dirty_rectangle(x, y, width, height)`: Marks a rectangle as dirty. - `set_device_offset(x, y)`: Sets the device offset. - `set_device_scale(x, y)`: Sets the device scale. - `set_fallback_resolution(x_pixels, y_pixels)`: Sets the fallback resolution. - `set_mime_data(mime_type, data)`: Sets MIME data for the surface. - `show_page()`: Shows the current page. - `supports_mime_type(mime_type)`: Checks if the surface supports a given MIME type. - `write_to_png(filename)`: Writes the surface content to a PNG file. ### `ImageSurface` Class Inherits from `Surface`. #### Static Methods - `create_for_data(data, format, width, height, stride)`: Creates an image surface from raw data. - `create_from_png(filename)`: Creates an image surface from a PNG file. - `format_stride_for_width(format, width)`: Calculates the stride for a given format and width. #### Methods - `get_data()`: Returns the raw image data. - `get_format()`: Returns the image format. - `get_height()`: Returns the image height. - `get_stride()`: Returns the image stride. - `get_width()`: Returns the image width. ### `PDFSurface` Class Inherits from `Surface`. #### Methods - `add_outline(name, flags)`: Adds an outline entry to the PDF. - `get_versions()`: Gets the available PDF versions. - `restrict_to_version(version)`: Restricts the PDF to a specific version. - `set_metadata(key, value)`: Sets metadata for the PDF. - `set_page_label(label)`: Sets the label for the current page. - `set_size(width, height)`: Sets the size of the PDF page. - `set_thumbnail_size(width, height)`: Sets the thumbnail size. - `version_to_string(version)`: Converts a PDF version to a string. ### `PSSurface` Class Inherits from `Surface`. #### Methods - `dsc_begin_page_setup()`: Begins page setup for DSC. - `dsc_begin_setup()`: Begins setup for DSC. - `dsc_comment(comment)`: Adds a DSC comment. - `get_eps()`: Checks if the surface is set to EPS. - `get_levels()`: Gets the available PostScript levels. - `ps_level_to_string(level)`: Converts a PostScript level to a string. - `restrict_to_level(level)`: Restricts the PostScript output to a specific level. - `set_eps(eps)`: Sets the surface to EPS mode. - `set_size(width, height)`: Sets the size of the PostScript page. ### `SVGSurface` Class Inherits from `Surface`. #### Methods - `get_document_unit(unit)`: Gets the document unit. - `get_versions()`: Gets the available SVG versions. - `restrict_to_version(version)`: Restricts the SVG output to a specific version. - `set_document_unit(unit)`: Sets the document unit. - `version_to_string(version)`: Converts an SVG version to a string. ### `RecordingSurface` Class Inherits from `Surface`. #### Methods - `get_extents()`: Gets the extents of the recorded content. - `ink_extents()`: Gets the ink extents of the recorded content. ### `Win32PrintingSurface` Class Inherits from `Surface`. (No specific methods documented in the provided text.) ``` -------------------------------- ### ImageSurface Constructor Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Creates an image surface of the specified format and dimensions. Optionally initializes with provided data. ```APIDOC ## ImageSurface Constructor ### Description Creates an image surface of the specified format and dimensions. If `data` is provided, its initial contents will be used. Otherwise, the surface contents are initialized to 0. ### Parameters - **format** (str) - Pixel format string for the surface to create. - **width** (int) - Width of the surface, in pixels. - **height** (int) - Height of the surface, in pixels. - **data** - Buffer supplied in which to write contents, or `None` to create a new buffer. - **stride** (int) - The number of bytes between the start of rows in the buffer. Should be computed by `format_stride_for_width()`. ``` -------------------------------- ### show_text Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Renders a string of text using the current font settings. ```APIDOC ## show_text ### Description A drawing operator that generates the shape from a string text, rendered according to the current font face, size, and options. ### Parameters - **text** (string) - Required - The text to show, as an Unicode or UTF-8 string. ``` -------------------------------- ### Surface Transformation Settings Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for setting device offsets, scales, and fallback resolutions for the surface. ```APIDOC ## PUT /surface/device_offset ### Description Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. This affects drawing to the surface as well as using the surface in a source pattern. ### Method PUT ### Endpoint /surface/device_offset ### Parameters #### Request Body - **x_offset** (float) - Required - The offset in the X direction, in device units. - **y_offset** (float) - Required - The offset in the Y direction, in device units. ### Request Example ```json { "x_offset": 10.0, "y_offset": 5.0 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Device offset set successfully." } ``` ## PUT /surface/device_scale ### Description Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface. This affects drawing to the surface as well as using the surface in a source pattern. ### Method PUT ### Endpoint /surface/device_scale ### Parameters #### Request Body - **x_scale** (float) - Required - The scale in the X direction, in device units. - **y_scale** (float) - Required - The scale in the Y direction, in device units. ### Request Example ```json { "x_scale": 2.0, "y_scale": 2.0 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Device scale set successfully." } ``` ## PUT /surface/fallback_resolution ### Description Set the horizontal and vertical resolution for image fallbacks. Larger values result in more detailed images but also larger file sizes. ### Method PUT ### Endpoint /surface/fallback_resolution ### Parameters #### Request Body - **x_pixels_per_inch** (float) - Required - The horizontal resolution in pixels per inch. - **y_pixels_per_inch** (float) - Required - The vertical resolution in pixels per inch. ### Request Example ```json { "x_pixels_per_inch": 300.0, "y_pixels_per_inch": 300.0 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Fallback resolution set successfully." } ``` ``` -------------------------------- ### Wrapper Factory Methods Source: https://doc.courtbouillon.org/cairocffi/stable/cffi_api.html Static methods to wrap existing cairo C pointers into Python wrapper classes. ```APIDOC ## Wrapper Factory Methods ### Description Methods used to create Python wrapper instances from existing cairo C pointers. ### Methods - **Surface._from_pointer(pointer, incref)** - Wraps a `cairo_surface_t *`. - **Pattern._from_pointer(pointer, incref)** - Wraps a `cairo_pattern_t *`. - **FontFace._from_pointer(pointer, incref)** - Wraps a `cairo_font_face_t *`. - **ScaledFont._from_pointer(pointer, incref)** - Wraps a `cairo_scaled_font_t *`. - **Context._from_pointer(pointer, incref)** - Wraps a `cairo_t *`. ### Parameters - **pointer** (cdata) - Required - The cairo C pointer to wrap. - **incref** (bool) - Required - Whether to increase the reference count upon wrapping. ``` -------------------------------- ### Surface State and Properties Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for retrieving information about the surface's content, device transformations, font options, and MIME data. ```APIDOC ## GET /surface/content ### Description Returns the Content string of this surface, which indicates whether the surface contains color and/or alpha information. ### Method GET ### Endpoint /surface/content ### Response #### Success Response (200) - **content** (string) - The content type of the surface (e.g., 'color', 'alpha'). #### Response Example ```json { "content": "color" } ``` ## GET /surface/device_offset ### Description Returns the previous device offset set by `set_device_offset()`. ### Method GET ### Endpoint /surface/device_offset ### Response #### Success Response (200) - **x_offset** (float) - The previous X offset. - **y_offset** (float) - The previous Y offset. #### Response Example ```json { "x_offset": 10.0, "y_offset": 5.0 } ``` ## GET /surface/device_scale ### Description Returns the previous device scale set by `set_device_scale()`. ### Method GET ### Endpoint /surface/device_scale ### Response #### Success Response (200) - **x_scale** (float) - The previous X scale factor. - **y_scale** (float) - The previous Y scale factor. #### Response Example ```json { "x_scale": 2.0, "y_scale": 2.0 } ``` ## GET /surface/fallback_resolution ### Description Returns the previous fallback resolution set by `set_fallback_resolution()`, or default fallback resolution if never set. ### Method GET ### Endpoint /surface/fallback_resolution ### Response #### Success Response (200) - **x_pixels_per_inch** (float) - The X resolution in pixels per inch. - **y_pixels_per_inch** (float) - The Y resolution in pixels per inch. #### Response Example ```json { "x_pixels_per_inch": 300.0, "y_pixels_per_inch": 300.0 } ``` ## GET /surface/font_options ### Description Retrieves the default font rendering options for the surface. ### Method GET ### Endpoint /surface/font_options ### Response #### Success Response (200) - **font_options** (object) - A FontOptions object containing font rendering settings. #### Response Example ```json { "font_options": { "subpixel_order": "rgb", "hinting": "slight", "antialias": "subpixel" } } ``` ## GET /surface/mime_data/{mime_type} ### Description Return mime data previously attached to surface using the specified mime type. ### Method GET ### Endpoint /surface/mime_data/{mime_type} ### Parameters #### Path Parameters - **mime_type** (string) - Required - The MIME type of the image data. ### Response #### Success Response (200) - **mime_data** (buffer) - A CFFI buffer object containing the MIME data, or null if no data is found. #### Response Example ```json { "mime_data": "" } ``` ## GET /surface/supports_show_text_glyphs ### Description Returns whether the surface supports sophisticated `Context.show_text_glyphs()` operations. ### Method GET ### Endpoint /surface/supports_show_text_glyphs ### Response #### Success Response (200) - **supports_show_text_glyphs** (boolean) - True if the surface supports sophisticated text glyph operations, false otherwise. #### Response Example ```json { "supports_show_text_glyphs": true } ``` ``` -------------------------------- ### Module-level Objects Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/cffi_api.rst.txt Accessing the underlying FFI instance and the pre-loaded libcairo library. ```APIDOC ## Module-level Objects ### Description Access the low-level cairo C API using the `ffi` instance or the pre-loaded `cairo` library object. ### Objects - **ffi** (cffi.FFI) - An FFI instance with all cairo C API declared. - **cairo** (libcairo) - The libcairo library, pre-loaded with `ffi.dlopen()`. ``` -------------------------------- ### Pango C API Access with CFFI and cairocffi Source: https://doc.courtbouillon.org/cairocffi/stable/cffi_api.html This snippet shows how to define C types and functions from Pango and GLib using CFFI, load dynamic libraries, and manage C object references. It's useful for advanced text rendering scenarios with cairocffi. ```python import cffi import cairocffi ffi = cffi.FFI() ffi.cdef('' /* GLib */ typedef void cairo_t; typedef void* gpointer; void g_object_unref (gpointer object); /* Pango and Pango Cairo */ typedef ... PangoLayout; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; int pango_units_from_double (double d); PangoLayout * pango_cairo_create_layout (cairo_t *cr); void pango_cairo_show_layout (cairo_t *cr, PangoLayout *layout); void pango_layout_set_width (PangoLayout *layout, int width); void pango_layout_set_alignment ( PangoLayout *layout, PangoAlignment alignment); void pango_layout_set_markup ( PangoLayout *layout, const char *text, int length); '') gobject = ffi.dlopen('gobject-2.0') pango = ffi.dlopen('pango-1.0') pangocairo = ffi.dlopen('pangocairo-1.0') def gobject_ref(pointer): return ffi.gc(pointer, gobject.g_object_unref) units_from_double = pango.pango_units_from_double def write_example_pdf(target): pt_per_mm = 72 / 25.4 width, height = 210 * pt_per_mm, 297 * pt_per_mm # A4 portrait surface = cairocffi.PDFSurface(target, width, height) context = cairocffi.Context(surface) context.translate(0, 300) context.rotate(-0.2) layout = gobject_ref( pangocairo.pango_cairo_create_layout(context._pointer)) pango.pango_layout_set_width(layout, units_from_double(width)) pango.pango_layout_set_alignment(layout, pango.PANGO_ALIGN_CENTER) markup = 'Hi from Παν語!' markup = ffi.new('char[]', markup.encode('utf8')) pango.pango_layout_set_markup(layout, markup, -1) pangocairo.pango_cairo_show_layout(context._pointer, layout) if __name__ == '__main__': write_example_pdf(target='pango_example.pdf') ``` -------------------------------- ### Draw an Ellipse using arc() Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Demonstrates how to draw an ellipse by scaling the transformation matrix before calling the arc method. ```python from math import pi with context: context.translate(x + width / 2., y + height / 2.) context.scale(width / 2., height / 2.) context.arc(0, 0, 1, 0, 2 * pi) ``` -------------------------------- ### PDFSurface Class Methods Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for managing PDF surface creation, configuration, and document-level settings. ```APIDOC ## PDFSurface ### Description Creates a PDF surface of the specified size in PostScript points to be written to a target. ### Parameters - **target** (string/file) - Required - A filename, a binary mode file object, or None. - **width_in_points** (float) - Required - Width of the surface in points. - **height_in_points** (float) - Required - Height of the surface in points. ## add_outline ### Description Add an item to the document outline hierarchy. ### Parameters - **parent_id** (int) - Required - The id of the parent item or PDF_OUTLINE_ROOT. - **utf8** (string) - Required - The name of the outline. - **link_attribs** (dict) - Required - Link attributes. - **flags** (int) - Optional - Outline item flags. ### Response - **id** (int) - The id for the added item. ## restrict_to_version ### Description Restricts the generated PDF file to a specific version. ### Parameters - **version** (string) - Required - A PDF version string. ## set_metadata ### Description Sets document metadata such as creation date or modification date. ### Parameters - **metadata** (string) - Required - The metadata item to set. - **utf8** (string) - Required - Metadata value. ## set_size ### Description Changes the size of a PDF surface for the current and subsequent pages. ### Parameters - **width_in_points** (float) - Required - New width of the page. - **height_in_points** (float) - Required - New height of the page. ``` -------------------------------- ### Import all from cairocffi Source: https://doc.courtbouillon.org/cairocffi/stable/overview.html This approach allows importing all names from cairocffi into the current namespace, effectively replacing Pycairo. Ensure 'cairo.py' is in your sys.path. ```python from cairocffi import * ``` -------------------------------- ### SolidPattern API Source: https://doc.courtbouillon.org/cairocffi/stable/api.html API for creating and interacting with solid color patterns. ```APIDOC ## POST /pattern/solid ### Description Creates a new pattern corresponding to a solid color. ### Method POST ### Parameters #### Request Body - **red** (float) - Required - Red component (0-1). - **green** (float) - Required - Green component (0-1). - **blue** (float) - Required - Blue component (0-1). - **alpha** (float) - Optional - Alpha component (0-1, default 1). ## GET /pattern/solid/rgba ### Description Returns the solid pattern's color components. ### Method GET ### Response #### Success Response (200) - **rgba** (tuple) - A (red, green, blue, alpha) tuple of floats. ``` -------------------------------- ### Image Loading with GDK-PixBuf Source: https://doc.courtbouillon.org/cairocffi/stable/_sources/pixbuf.rst.txt This section details how to use the cairocffi.pixbuf module to decode various image formats using GDK-PixBuf. It also explains the pixel conversion process and potential performance considerations. ```APIDOC ## Decoding images with GDK-PixBuf ### Description The :mod:`cairocffi.pixbuf` module utilizes the GDK-PixBuf library to decode image formats such as JPEG, GIF, and others, depending on the installed GDK-PixBuf version and system configuration. Importing this module is optional; cairocffi can function without it if GDK-PixBuf is not installed. GDK-PixBuf has been an independent package since version 2.22, previously being part of GTK+. ### Pixel Conversion This module also handles the conversion of pixel data. GDK-PixBuf uses big-endian RGBA format, while cairo uses native-endian ARGB format. This conversion is necessary for compatibility. While :meth:`ImageSurface.create_from_png()` might be faster for PNGs, :func:`decode_to_image_surface` is used for other formats. The pixel conversion is performed by GTK+ if available; otherwise, a slower fallback method is employed. ### Exceptions - **ImageLoadingError**: An exception raised during image loading. ### Functions - **decode_to_image_surface()**: Decodes an image file into a cairo ImageSurface using GDK-PixBuf. ``` -------------------------------- ### Replay a RecordingSurface Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Use this pattern to replay recorded drawing operations onto a target surface. ```python context = Context(target) context.set_source_surface(recording_surface, 0, 0) context.paint() ``` -------------------------------- ### Initialize Matrix with Rotation Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Use this class method to create a new Matrix object that represents a rotation transformation by a specified angle in radians. ```python Matrix.init_rotate(radians) ``` -------------------------------- ### PostScript Surface Configuration Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for configuring PostScript surface properties such as EPS mode and page size. ```APIDOC ## set_eps(eps) ### Description If eps is True, the PostScript surface will output Encapsulated PostScript. This method should only be called before any drawing operations have been performed on the current page. ### Parameters #### Request Body - **eps** (boolean) - Required - If True, output Encapsulated PostScript. ## set_size(width_in_points, height_in_points) ### Description Changes the size of a PostScript surface for the current and subsequent pages. ### Parameters #### Request Body - **width_in_points** (float) - Required - New width of the page, in points (1 point == 1/72.0 inch). - **height_in_points** (float) - Required - New height of the page, in points (1 point == 1/72.0 inch). ``` -------------------------------- ### CFFI Wrapper API Source: https://doc.courtbouillon.org/cairocffi/stable/index.html Methods for managing Cairo object pointers and interoperability between pycairo and cairocffi. ```APIDOC ## CFFI Wrapper Methods ### Description Methods to create wrappers from pointers or access underlying pointers for various Cairo objects. ### Methods - **Surface._from_pointer()** - **Pattern._from_pointer()** - **FontFace._from_pointer()** - **ScaledFont._from_pointer()** - **Context._from_pointer()** ### Properties - **_pointer** - Available for Surface, Pattern, FontFace, ScaledFont, FontOptions, Matrix, and Context objects. ``` -------------------------------- ### ToyFontFace Methods Source: https://doc.courtbouillon.org/cairocffi/stable/api.html Methods for retrieving font face properties. ```APIDOC ## ToyFontFace Methods ### get_family() #### Description Return this font face’s family name. ### get_slant() #### Description Return this font face’s Font slant string. ### get_weight() #### Description Return this font face’s Font weight string. ```