# Surfaces

## class Surface()

class cairo.Surface

  cairo.Surface is the abstract type representing all different drawing targets that cairo can render to. The actual drawings are performed using a `Context`.

  A cairo.Surface is created by using backend-specific constructors of the form cairo.<XXX>Surface().

  Surface is the abstract base class from which all the other surface classes derive. It cannot be instantiated directly.

  Note

  Added in version 1.17.0: `cairo.Surface` can be used as a context manager:

      # surface.finish() will be called on __exit__
      with cairo.SVGSurface("example.svg", 200, 200) as surface:
          pass

      # surface.unmap_image(image_surface) will be called on __exit__
      with surface.map_to_image(None) as image_surface:
          pass

  __init__()
  copy_page() → None

    Emits the current page for backends that support multiple pages, but doesn’t clear it, so that the contents of the current page will be retained for the next page. Use `show_page()` if you want to get an empty page after the emission.

    `Context.copy_page()` is a convenience function for this.

    Added in version 1.6.

  create_for_rectangle(x: float, y: float, width: float, height: float) → Surface
    Parameters:

      - x – the x-origin of the sub-surface from the top-left of the target surface (in device-space units)

      - y – the y-origin of the sub-surface from the top-left of the target surface (in device-space units)

      - width – width of the sub-surface (in device-space units)

      - height – height of the sub-surface (in device-space units)

    Returns:

      a new surface

    Create a new surface that is a rectangle within the target surface. All operations drawn to this surface are then clipped and translated onto the target surface. Nothing drawn via this sub-surface outside of its bounds is drawn onto the target surface, making this a useful method for passing constrained child surfaces to library routines that draw directly onto the parent surface, i.e. with no further backend allocations, double buffering or copies.

    Note

    The semantics of subsurfaces have not been finalized yet unless the rectangle is in full device units, is contained within the extents of the target surface, and the target or subsurface’s device transforms are not changed.

    Added in version 1.12.0.

  create_similar(content: Content, width: int, height: int) → Surface
    Parameters:

      - content – the content for the new surface

      - width – width of the new surface, (in device-space units)

      - height – height of the new surface (in device-space units)

    Returns:

      a newly allocated Surface.

    Create a Surface that is as compatible as possible with the existing surface. For example the new surface will have the same fallback resolution and `FontOptions`. Generally, the new surface will also use the same backend, unless that is not possible for some reason.

    Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

  create_similar_image(format: Format, width: int, height: int) → ImageSurface
    Parameters:

      - format (cairo.Format) – the format for the new surface

      - width – width of the new surface, (in device-space units)

      - height – height of the new surface, (in device-space units)

    Returns:

      a new image surface

    Create a new image surface that is as compatible as possible for uploading to and the use in conjunction with an existing surface. However, this surface can still be used like any normal image surface.

    Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

    Added in version 1.12.0.

  finish() → None

    This method finishes the Surface and drops all references to external resources. For example, for the Xlib backend it means that cairo will no longer access the drawable, which can be freed. After calling finish() the only valid operations on a Surface are flushing and finishing it. Further drawing to the surface will not affect the surface but will instead trigger a cairo.Error exception.

  flush() → None

    Do any pending drawing for the Surface and also restore any temporary modification’s cairo has made to the Surface’s state. This method must be called before switching from drawing on the Surface with cairo to drawing on it directly with native APIs. If the Surface doesn’t support direct access, then this function does nothing.

  get_content() → Content
    Returns:

      The content type of Surface, which indicates whether the Surface contains color and/or alpha information.

    Added in version 1.2.

  get_device() → Device | None
    Returns:

      the device or `None` if the surface does not have an associated device

    This function returns the device for a surface.

    Added in version 1.14.0.

  get_device_offset() → Tuple[float, float]
    Returns:

      (x_offset, y_offset) a tuple of float

      - x_offset: the offset in the X direction, in device units

      - y_offset: the offset in the Y direction, in device units

    This method returns the previous device offset set by `set_device_offset()`.

    Added in version 1.2.

  get_device_scale() → Tuple[float, float]
    Returns:

      (x_scale,y_scale) a 2-tuple of float

    This function returns the previous device offset set by `Surface.set_device_scale()`.

    Added in version 1.14.0.

  get_fallback_resolution() → Tuple[float, float]
    Returns:

      (x_pixels_per_inch, y_pixels_per_inch) a tuple of float

      - x_pixels_per_inch: horizontal pixels per inch

      - y_pixels_per_inch: vertical pixels per inch

    This method returns the previous fallback resolution set by `set_fallback_resolution()`, or default fallback resolution if never set.

    Added in version 1.8.

  get_font_options() → FontOptions
    Returns:

      a `FontOptions`

    Retrieves the default font rendering options for the Surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with `ScaledFont`.

  get_mime_data(mime_type: str) → bytes | None
    Parameters:

      mime_type – the MIME type of the image data (cairo.MIME_TYPE)

    Returns:

      `bytes` or `None`

    Return mime data previously attached to surface with `set_mime_data()` using the specified mime type. If no data has been attached with the given mime type, `None` is returned.

    Added in version 1.12.0.

  has_show_text_glyphs() → bool
    Returns:

      `True` if surface supports `Context.show_text_glyphs()`, `False` otherwise

    Returns whether the surface supports sophisticated `Context.show_text_glyphs()` operations. That is, whether it actually uses the provided text and cluster data to a `Context.show_text_glyphs()` call.

    Note: Even if this function returns `False`, a `Context.show_text_glyphs()` operation targeted at surface will still succeed. It just will act like a `Context.show_glyphs()` operation. Users can use this function to avoid computing UTF-8 text and cluster mapping if the target surface does not use it.

    Added in version 1.12.0.

  map_to_image(extents: RectangleInt | None) → ImageSurface
    Parameters:

      extents – limit the extraction to an rectangular region or `None` for the whole surface

    Returns:

      newly allocated image surface

    Raises:

      Error –

    Returns an image surface that is the most efficient mechanism for modifying the backing store of the target surface.

    Note, the use of the original surface as a target or source whilst it is mapped is undefined. The result of mapping the surface multiple times is undefined. Calling `Surface.finish()` on the resulting image surface results in undefined behavior. Changing the device transform of the image surface or of surface before the image surface is unmapped results in undefined behavior.

    The caller must use `Surface.unmap_image()` to destroy this image surface.

    Added in version 1.15.0.

  mark_dirty() → None

    Tells cairo that drawing has been done to Surface using means other than cairo, and that cairo should reread any cached areas. Note that you must call `flush()` before doing such drawing.

  mark_dirty_rectangle(x: int, y: int, width: int, height: int) → None
    Parameters:

      - x – X coordinate of dirty rectangle

      - y – Y coordinate of dirty rectangle

      - width – width of dirty rectangle

      - height – height of dirty rectangle

    Like `mark_dirty()`, but drawing has been done only to the specified rectangle, so that cairo can retain cached contents for other parts of the surface.

    Any cached clip set on the Surface will be reset by this function, to make sure that future cairo calls have the clip set that they expect.

  set_device_offset(x_offset: float, y_offset: float) → None
    Parameters:

      - x_offset – the offset in the X direction, in device units

      - y_offset – the offset in the Y direction, in device units

    Sets an offset that is added to the device coordinates determined by the CTM when drawing to Surface. One use case for this function is when we want to create a Surface that redirects drawing for a portion of an onscreen surface to an offscreen surface in a way that is completely invisible to the user of the cairo API. Setting a transformation via `Context.translate()` isn’t sufficient to do this, since functions like `Context.device_to_user()` will expose the hidden offset.

    Note that the offset affects drawing to the surface as well as using the surface in a source pattern.

  set_device_scale(x_scale: float, y_scale: float) → None
    Parameters:

      - x_scale – a scale factor in the X direction

      - y_scale – a scale factor in the Y direction

    Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface . One common use for this is to render to very high resolution display devices at a scale factor, so that code that assumes 1 pixel will be a certain size will still work. Setting a transformation via `Context.translate()` isn’t sufficient to do this, since functions like `Context.device_to_user()` will expose the hidden scale.

    Added in version 1.14.0.

  set_fallback_resolution(x_pixels_per_inch: float, y_pixels_per_inch: float) → None
    Parameters:

      - x_pixels_per_inch – horizontal setting for pixels per inch

      - y_pixels_per_inch – vertical setting for pixels per inch

    Set the horizontal and vertical resolution for image fallbacks.

    When certain operations aren’t supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, this function can be used to set the resolution used for these image fallbacks, (larger values will result in more detailed images, but also larger file sizes).

    Some examples of natively vector-oriented backends are the ps, pdf, and svg backends.

    For backends that are natively raster-oriented, image fallbacks are still possible, but they are always performed at the native device resolution. So this function has no effect on those backends.

    Note: The fallback resolution only takes effect at the time of completing a page (with `Context.show_page()` or `Context.copy_page()`) so there is currently no way to have more than one fallback resolution in effect on a single page.

    The default fallback resoultion is 300 pixels per inch in both dimensions.

    Added in version 1.2.

  set_mime_data(mime_type: str, data: bytes) → None
    Parameters:

      - mime_type – the MIME type of the image data (cairo.MIME_TYPE)

      - data – the image data to attach to the surface

    Attach an image in the format `mime_type` to Surface. To remove the data from a surface, call this function with same mime type and `None` for data.

    The attached image (or filename) data can later be used by backends which support it (currently: PDF, PS, SVG and Win32 Printing surfaces) to emit this data instead of making a snapshot of the surface. This approach tends to be faster and requires less memory and disk space.

    The recognized MIME types are listed under cairo.MIME_TYPE.

    See corresponding backend surface docs for details about which MIME types it can handle. Caution: the associated MIME data will be discarded if you draw on the surface afterwards. Use this function with care.

    Added in version 1.12.0.

  show_page() → None

    Emits and clears the current page for backends that support multiple pages. Use `copy_page()` if you don’t want to clear the page.

    There is a convenience function for this that takes a `Context.show_page()`.

    Added in version 1.6.

  supports_mime_type(mime_type: str) → bool
    Parameters:

      mime_type – the mime type (cairo.MIME_TYPE)

    Returns:

      `True` if surface supports mime_type, `False` otherwise

    Return whether surface supports `mime_type`.

    Added in version 1.12.0.

  write_to_png(fobj: TypeAliasForwardRef('cairo._FileLike') | TypeAliasForwardRef('cairo._PathLike')) → None
    Parameters:

      fobj – a filename or writable file object

    Raises:

      `MemoryError` if memory could not be allocated for the operation

      `IOError` if an I/O error occurs while attempting to write the file

    Writes the contents of Surface to fobj as a PNG image. fobj can either be a filename or a file object opened in binary mode.

  unmap_image(image: ImageSurface) → None
    Parameters:

      image – the currently mapped image

    Unmaps the image surface as returned from `Surface.map_to_image()`.

    The content of the image will be uploaded to the target surface. Afterwards, the image is destroyed.

    Using an image surface which wasn’t returned by `Surface.map_to_image()` results in undefined behavior.

    Added in version 1.15.0.

## class ImageSurface(`Surface`)

class cairo.ImageSurface(format: Format, width: int, height: int)

  A cairo.ImageSurface provides the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in `cairo.Format`.

  __init__(format: Format, width: int, height: int) → None
    Parameters:

      - format – format of pixels in the surface to create

      - width – width of the surface, in pixels

      - height – height of the surface, in pixels

    Returns:

      a new ImageSurface

    Creates an ImageSurface of the specified format and dimensions. Initially the surface contents are all 0. (Specifically, within each pixel, each color or alpha channel belonging to format will be 0. The contents of bits within a pixel, but not belonging to the given format are undefined).

  classmethod create_for_data(data: memoryview, format: Format, width: int, height: int, stride: int = Ellipsis) → ImageSurface
    Parameters:

      - data – a writable Python buffer/memoryview object

      - format – the format of pixels in the buffer

      - width – the width of the image to be stored in the buffer

      - height – the height of the image to be stored in the buffer

      - stride – the number of bytes between the start of rows in the buffer as allocated. If not given the value from `cairo.Format.stride_for_width()` is used.

    Returns:

      a new ImageSurface

    Raises:

      `MemoryError` in case of no memory.

      `cairo.Error` in case of invalid stride value.

    Creates an ImageSurface for the provided pixel data. The initial contents of buffer will be used as the initial image contents; you must explicitly clear the buffer, using, for example, cairo_rectangle() and cairo_fill() if you want it cleared.

    Note that the stride may be larger than width*bytes_per_pixel to provide proper alignment for each pixel and row. This alignment is required to allow high-performance rendering within cairo. The correct way to obtain a legal stride value is to call `cairo.Format.stride_for_width()` with the desired format and maximum image width value, and use the resulting stride value to allocate the data and to create the `ImageSurface`. See `cairo.Format.stride_for_width()` for example code.

  classmethod create_from_png(fobj: TypeAliasForwardRef('cairo._PathLike') | TypeAliasForwardRef('cairo._FileLike')) → ImageSurface
    Parameters:

      fobj – a `_PathLike`, file, or file-like object of the PNG to load.

    Returns:

      a new ImageSurface initialized the contents to the given PNG file.

    Creates a new image surface and initializes the contents to the given PNG file. fobj can either be a filename or a file object opened in binary mode.

  format_stride_for_width(width: int) → int

    See `cairo.Format.stride_for_width()`.

    Added in version 1.6.

  get_data() → memoryview
    Returns:

      a Python buffer object for the data of the ImageSurface, for direct inspection or modification. On Python 3 a memoryview object is returned.

    Added in version 1.2.

  get_format() → Format
    Returns:

      the format of the ImageSurface.

    Return type:

      cairo.Format

    Added in version 1.2.

  get_height() → int
    Returns:

      the height of the ImageSurface in pixels.

  get_stride() → int
    Returns:

      the stride of the ImageSurface in bytes. The stride is the distance in bytes from the beginning of one row of the image data to the beginning of the next row.

  get_width() → int
    Returns:

      the width of the ImageSurface in pixels.

## class PDFSurface(`Surface`)

class cairo.PDFSurface(fobj: TypeAliasForwardRef('cairo._PathLike') | TypeAliasForwardRef('cairo._FileLike'), width_in_points: float, height_in_points: float)

  The PDFSurface is used to render cairo graphics to Adobe PDF files and is a multi-page vector surface backend.

  Added in version 1.2.

  __init__(fobj: TypeAliasForwardRef('cairo._PathLike') | TypeAliasForwardRef('cairo._FileLike'), width_in_points: float, height_in_points: float) → None
    Parameters:

      - fobj – a filename or writable file object. None may be used to specify no output. This will generate a PDFSurface that may be queried and used as a source, without generating a temporary file.

      - width_in_points – width of the surface, in points (1 point == 1/72.0 inch)

      - height_in_points – height of the surface, in points (1 point == 1/72.0 inch)

    Returns:

      a new PDFSurface of the specified size in points to be written to fobj.

    Added in version 1.2.

  set_custom_metadata(name: str, value: str | None) → None
    Parameters:

      - name – The name of the custom metadata item to set.

      - value – The value of the metadata.

    Set custom document metadata. name may be any string except for the following names reserved by PDF: “Title”, “Author”, “Subject”, “Keywords”, “Creator”, “Producer”, “CreationDate”, “ModDate”, “Trapped”.

    If value is `None` or an empty string, the name metadata will not be set.

    For example:

        surface.set_custom_metadata("ISBN", "978-0123456789")

    Added in version 1.23.0: Only available with cairo 1.17.6+

  set_size(width_in_points: float, height_in_points: float) → None
    Parameters:

      - width_in_points – new surface width, in points (1 point == 1/72.0 inch)

      - height_in_points – new surface height, in points (1 point == 1/72.0 inch)

    Changes the size of a PDFSurface for the current (and subsequent) pages.

    This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either `Context.show_page()` or `Context.copy_page()`.

    Added in version 1.2.

  restrict_to_version(version: PDFVersion) → None
    Parameters:

      version – PDF version

    Restricts the generated PDF file to version . See `get_versions()` for a list of available version values that can be used here.

    This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.

    Added in version 1.12.0.

  static get_versions() → List[PDFVersion]
    Returns:

      supported version list

    Retrieve the list of supported versions. See `restrict_to_version()`.

    Added in version 1.12.0.

  static version_to_string(version: PDFVersion) → str
    Parameters:

      version – PDF version

    Returns:

      the string associated to the given version

    Raises:

      ValueError – if version isn’t valid

    Get the string representation of the given version id. See `get_versions()` for a way to get the list of valid version ids.

    Added in version 1.12.0.

  add_outline(parent_id: int, utf8: str, link_attribs: str, flags: PDFOutlineFlags) → int
    Parameters:

      - parent_id – the id of the parent item or `PDF_OUTLINE_ROOT` if this is a top level item.

      - utf8 – the name of the outline

      - link_attribs – the link attributes specifying where this outline links to

      - flags – outline item flags

    Returns:

      the id for the added item.

    Added in version 1.18.0: Only available with cairo 1.15.10+

  set_metadata(metadata: PDFMetadata, utf8: str) → None
    Parameters:

      - metadata – The metadata item to set.

      - utf8 – metadata value

    Set document metadata. The `PDFMetadata.CREATE_DATE` and `PDFMetadata.MOD_DATE` values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional timezone of the form “[+/-]hh:mm” or “Z” for UTC time can be appended. All other metadata values can be any UTF-8 string.

    Added in version 1.18.0: Only available with cairo 1.15.10+

  set_page_label(utf8: str) → None
    Parameters:

      utf8 – metadata value

    Set page label for the current page.

    Added in version 1.18.0: Only available with cairo 1.15.10+

  set_thumbnail_size(width: int, height: int) → None
    Parameters:

      - width – Thumbnail width.

      - height – Thumbnail height

    Set the thumbnail image size for the current and all subsequent pages. Setting a width or height of 0 disables thumbnails for the current and subsequent pages.

    Added in version 1.18.0: Only available with cairo 1.15.10+

## class PSSurface(`Surface`)

class cairo.PSSurface(fobj: TypeAliasForwardRef('cairo._FileLike') | TypeAliasForwardRef('cairo._PathLike'), width_in_points: float, height_in_points: float)

  The PSSurface is used to render cairo graphics to Adobe PostScript files and is a multi-page vector surface backend.

  __init__(fobj: TypeAliasForwardRef('cairo._FileLike') | TypeAliasForwardRef('cairo._PathLike'), width_in_points: float, height_in_points: float) → None
    Parameters:

      - fobj – a filename or writable file object. None may be used to specify no output. This will generate a PSSurface that may be queried and used as a source, without generating a temporary file.

      - width_in_points – width of the surface, in points (1 point == 1/72.0 inch)

      - height_in_points – height of the surface, in points (1 point == 1/72.0 inch)

    Returns:

      a new PDFSurface of the specified size in points to be written to fobj.

    Raises:

      `MemoryError` in case of no memory

    Note that the size of individual pages of the PostScript output can vary. See `set_size()`.

  dsc_begin_page_setup() → None

    This method indicates that subsequent calls to `dsc_comment()` should direct comments to the PageSetup section of the PostScript output.

    This method call is only needed for the first page of a surface. It should be called after any call to `dsc_begin_setup()` and before any drawing is performed to the surface.

    See `dsc_comment()` for more details.

    Added in version 1.2.

  dsc_begin_setup() → None

    This function indicates that subsequent calls to `dsc_comment()` should direct comments to the Setup section of the PostScript output.

    This function should be called at most once per surface, and must be called before any call to `dsc_begin_page_setup()` and before any drawing is performed to the surface.

    See `dsc_comment()` for more details.

    Added in version 1.2.

  dsc_comment(comment: str) → None
    Parameters:

      comment – a comment string to be emitted into the PostScript output

    Emit a comment into the PostScript output for the given surface.

    The comment is expected to conform to the PostScript Language Document Structuring Conventions (DSC). Please see that manual for details on the available comments and their meanings. In particular, the %%IncludeFeature comment allows a device-independent means of controlling printer device features. So the PostScript Printer Description Files Specification will also be a useful reference.

    The comment string must begin with a percent character (%) and the total length of the string (including any initial percent characters) must not exceed 255 characters. Violating either of these conditions will place PSSurface into an error state. But beyond these two conditions, this function will not enforce conformance of the comment with any particular specification.

    The comment string should not have a trailing newline.

    The DSC specifies different sections in which particular comments can appear. This function provides for comments to be emitted within three sections: the header, the Setup section, and the PageSetup section. Comments appearing in the first two sections apply to the entire document while comments in the BeginPageSetup section apply only to a single page.

    For comments to appear in the header section, this function should be called after the surface is created, but before a call to `dsc_begin_setup()`.

    For comments to appear in the Setup section, this function should be called after a call to `dsc_begin_setup()` but before a call to `dsc_begin_page_setup()`.

    For comments to appear in the PageSetup section, this function should be called after a call to `dsc_begin_page_setup()`.

    Note that it is only necessary to call `dsc_begin_page_setup()` for the first page of any surface. After a call to `Context.show_page()` or `Context.copy_page()` comments are unambiguously directed to the PageSetup section of the current page. But it doesn’t hurt to call this function at the beginning of every page as that consistency may make the calling code simpler.

    As a final note, cairo automatically generates several comments on its own. As such, applications must not manually generate any of the following comments:

    Header section: %!PS-Adobe-3.0, %Creator, %CreationDate, %Pages, %BoundingBox, %DocumentData, %LanguageLevel, %EndComments.

    Setup section: %BeginSetup, %EndSetup

    PageSetup section: %BeginPageSetup, %PageBoundingBox, %EndPageSetup.

    Other sections: %BeginProlog, %EndProlog, %Page, %Trailer, %EOF

    Here is an example sequence showing how this function might be used:

        surface = PSSurface (filename, width, height)
        ...
        surface.dsc_comment (surface, "%%Title: My excellent document")
        surface.dsc_comment (surface, "%%Copyright: Copyright (C) 2006 Cairo Lover")
        ...
        surface.dsc_begin_setup (surface)
        surface.dsc_comment (surface, "%%IncludeFeature: *MediaColor White")
        ...
        surface.dsc_begin_page_setup (surface)
        surface.dsc_comment (surface, "%%IncludeFeature: *PageSize A3")
        surface.dsc_comment (surface, "%%IncludeFeature: *InputSlot LargeCapacity")
        surface.dsc_comment (surface, "%%IncludeFeature: *MediaType Glossy")
        surface.dsc_comment (surface, "%%IncludeFeature: *MediaColor Blue")
        ... draw to first page here ..
        ctx.show_page (cr)
        ...
        surface.dsc_comment (surface, "%%IncludeFeature:  PageSize A5");
        ...

    Added in version 1.2.

  get_eps() → bool
    Returns:

      True iff the PSSurface will output Encapsulated PostScript.

    Added in version 1.6.

  static level_to_string(level: PSLevel) → str
    Parameters:

      level – a PS level

    Returns:

      the string associated to given level.

    Get the string representation of the given level. See `get_levels()` for a way to get the list of valid level ids.

    Note

    Prior to 1.12 this was available under `ps_level_to_string()`

    Added in version 1.12.0.

  static ps_level_to_string(level: PSLevel) → str

    Alias for `level_to_string()`

    Added in version 1.6.

  restrict_to_level(level: PSLevel) → None
    Parameters:

      level – a PS level

    Restricts the generated PostSript file to level. See `get_levels()` for a list of available level values that can be used here.

    This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.

    Added in version 1.6.

  set_eps(eps: bool) → None
    Parameters:

      eps – True to output EPS format PostScript

    If eps is True, the PostScript surface will output Encapsulated PostScript.

    This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface. An Encapsulated PostScript file should never contain more than one page.

    Added in version 1.6.

  set_size(width_in_points: float, height_in_points: float) → None
    Parameters:

      - width_in_points – new surface width, in points (1 point == 1/72.0 inch)

      - height_in_points – new surface height, in points (1 point == 1/72.0 inch)

    Changes the size of a PostScript surface for the current (and subsequent) pages.

    This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either `Context.show_page()` or `Context.copy_page()`.

    Added in version 1.2.

  static get_levels() → List[PSLevel]
    Returns:

      supported level list

    Retrieve the list of supported levels. See `restrict_to_level()`.

    Added in version 1.12.0.

## class RecordingSurface(`Surface`)

class cairo.RecordingSurface(content: Content, rectangle: Rectangle)

  A RecordingSurface is a surface that records all drawing operations at the highest level of the surface backend interface, (that is, the level of paint, mask, stroke, fill, and show_text_glyphs). The recording surface can then be “replayed” against any target surface by using it as a source surface.

  If you want to replay a surface so that the results in target will be identical to the results that would have been obtained if the original operations applied to the recording surface had instead been applied to the target surface, you can use code like this:

      cr = cairo.Context(target)
      cr.set_source_surface(recording_surface, 0.0, 0.0)
      cr.paint()

  A RecordingSurface is logically unbounded, i.e. it has no implicit constraint on the size of the drawing surface. However, in practice this is rarely useful as you wish to replay against a particular target surface with known bounds. For this case, it is more efficient to specify the target extents to the recording surface upon creation.

  The recording phase of the recording surface is careful to snapshot all necessary objects (paths, patterns, etc.), in order to achieve accurate replay.

  Added in version 1.11.0.

  __init__(content: Content, rectangle: Rectangle) → None
    Parameters:

      - content – the content for the new surface

      - rectangle – or None to record unbounded operations.

    Creates a RecordingSurface which can be used to record all drawing operations at the highest level (that is, the level of paint, mask, stroke, fill and show_text_glyphs). The RecordingSurface can then be “replayed” against any target surface by using it as a source to drawing operations.

    The recording phase of the RecordingSurface is careful to snapshot all necessary objects (paths, patterns, etc.), in order to achieve accurate replay.

    Added in version 1.11.0.

  ink_extents() → Tuple[float, float, float, float]

    - x0: the x-coordinate of the top-left of the ink bounding box

    - y0: the y-coordinate of the top-left of the ink bounding box

    - width: the width of the ink bounding box

    - height: the height of the ink bounding box

    Measures the extents of the operations stored within the RecordingSurface. This is useful to compute the required size of an ImageSurface (or equivalent) into which to replay the full sequence of drawing operations.

    Added in version 1.11.0.

  get_extents() → Rectangle | None
    Returns:

      a rectangle or `None` if the surface is unbounded.

    Get the extents of the recording-surface.

    Added in version 1.12.0.

## class SVGSurface(`Surface`)

class cairo.SVGSurface(fobj: TypeAliasForwardRef('cairo._PathLike') | TypeAliasForwardRef('cairo._FileLike'), width_in_points: float, height_in_points: float)

  The SVGSurface is used to render cairo graphics to SVG files and is a multi-page vector surface backend

  __init__(fobj: TypeAliasForwardRef('cairo._PathLike') | TypeAliasForwardRef('cairo._FileLike'), width_in_points: float, height_in_points: float) → None
    Parameters:

      - fobj – a filename or writable file object. None may be used to specify no output. This will generate a SVGSurface that may be queried and used as a source, without generating a temporary file.

      - width_in_points – width of the surface, in points (1 point == 1/72.0 inch)

      - height_in_points – height of the surface, in points (1 point == 1/72.0 inch)

  restrict_to_version(version: SVGVersion) → None
    Parameters:

      version – SVG version

    Restricts the generated SVG file to version . See `get_versions()` for a list of available version values that can be used here.

    This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.

    Added in version 1.12.0.

  static get_versions() → List[SVGVersion]
    Returns:

      supported version list

    Retrieve the list of supported versions. See `restrict_to_version()`.

    Added in version 1.12.0.

  static version_to_string(version: SVGVersion) → str
    Parameters:

      version – SVG version

    Returns:

      the string associated to the given version

    Raises:

      ValueError – if version isn’t valid

    Get the string representation of the given version id. See `get_versions()` for a way to get the list of valid version ids.

    Added in version 1.12.0.

  get_document_unit() → SVGUnit
    Returns:

      the SVG unit of the SVG surface.

    Return type:

      SVGUnit

    Get the unit of the SVG surface.

    Added in version 1.18.0: Only available with cairo 1.15.10+

  set_document_unit(unit: SVGUnit) → None
    Parameters:

      unit (SVGUnit) – SVG unit

    Use the specified unit for the width and height of the generated SVG file. See `SVGUnit` for a list of available unit values that can be used here.

    This function can be called at any time before generating the SVG file.

    However to minimize the risk of ambiguities it’s recommended to call it before any drawing operations have been performed on the given surface, to make it clearer what the unit used in the drawing operations is.

    The simplest way to do this is to call this function immediately after creating the SVG surface.

    Note if this function is never called, the default unit for SVG documents generated by cairo will be “pt”. This is for historical reasons.

    Added in version 1.18.0: Only available with cairo 1.15.10+

## class Win32Surface(`Surface`)

class cairo.Win32Surface(hdc: int)

  The Microsoft Windows surface is used to render cairo graphics to Microsoft Windows windows, bitmaps, and printing device contexts.

  __init__(hdc: int) → None
    Parameters:

      hdc (int) – the DC to create a surface for

    Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. The resulting surface will always be of format cairo.FORMAT_RGB24, see `cairo.Format`.

## class Win32PrintingSurface(`Surface`)

class cairo.Win32PrintingSurface(hdc: int)

  The Win32PrintingSurface is a multi-page vector surface type.

  __init__(hdc: int) → None
    Parameters:

      hdc – the DC to create a surface for

    Returns:

      the newly created surface

    Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. The DC should be a printing DC; antialiasing will be ignored, and GDI will be used as much as possible to draw to the surface.

    The returned surface will be wrapped using the paginated surface to provide correct complex rendering behaviour; `cairo.Surface.show_page()` and associated methods must be used for correct output.

## class XCBSurface(`Surface`)

class cairo.XCBSurface(connection: Any, drawable: Any, visualtype: Any, width: int, height: int)

  The XCB surface is used to render cairo graphics to X Window System windows and pixmaps using the XCB library.

  Note that the XCB surface automatically takes advantage of the X render extension if it is available.

  __init__(connection: Any, drawable: Any, visualtype: Any, width: int, height: int) → None
    Parameters:

      - connection – an XCB connection

      - drawable – a X drawable

      - visualtype – a X visualtype

      - width – The surface width

      - height – The surface height

    Creates a cairo surface that targets the given drawable (pixmap or window).

    Note

    This type isn’t implemented. Please file a bug if you need it.

  set_size(width: int, height: int) → None
    Parameters:

      - width – The width of the surface

      - height – The height of the surface

    Informs cairo of the new size of the X Drawable underlying the surface. For a surface created for a Window (rather than a Pixmap), this function must be called each time the size of the window changes. (For a subwindow, you are normally resizing the window yourself, but for a toplevel window, it is necessary to listen for ConfigureNotify events.)

    A Pixmap can never change size, so it is never necessary to call this function on a surface created for a Pixmap.

## class XlibSurface(`Surface`)

class cairo.XlibSurface

  The XLib surface is used to render cairo graphics to X Window System windows and pixmaps using the XLib library.

  Note that the XLib surface automatically takes advantage of X render extension if it is available.

  Note

  XlibSurface cannot be instantiated directly because Python interaction with Xlib would require open source Python bindings to Xlib which provided a C API. However, an XlibSurface instance can be returned from a function call when using pygtk http://www.pygtk.org/.

  get_depth() → int
    Returns:

      the number of bits used to represent each pixel value.

    Added in version 1.2.

  get_height() → int
    Returns:

      the height of the X Drawable underlying the surface in pixels.

    Added in version 1.2.

  get_width() → int
    Returns:

      the width of the X Drawable underlying the surface in pixels.

    Added in version 1.2.

## class ScriptSurface(`Surface`)

class cairo.ScriptSurface(script: ScriptDevice, content: Content, width: float, height: float)

  The script surface provides the ability to render to a native script that matches the cairo drawing model. The scripts can be replayed using tools under the util/cairo-script directory, or with cairo-perf-trace.

  Added in version 1.14.

  __init__(script: ScriptDevice, content: Content, width: float, height: float) → None
    Parameters:

      - script – the script (output device)

      - content – the content of the surface

      - width – width in pixels

      - height – height in pixels

    Raises:

      cairo.Error –

    Create a new surface that will emit its rendering through `script`.

  classmethod create_for_target(script: ScriptDevice, target: Surface) → ScriptSurface
    Parameters:

      - script – the script (output device)

      - target – a target surface to wrap

    Raises:

      cairo.Error –

    Create a proxy surface that will render to `target` and record the operations to `device`.

    Added in version 1.14.

## class TeeSurface(`Surface`)

class cairo.TeeSurface(master: Surface)

  This surface supports redirecting all its input to multiple surfaces.

  Added in version 1.14.

  __init__(master: Surface) → None
  add(target: Surface) → None
    Parameters:

      target

    Raises:

      cairo.Error –

    Add the surface

    Added in version 1.14.

  remove(target: Surface) → None
    Parameters:

      target

    Raises:

      cairo.Error –

    Remove the surface

    Added in version 1.14.

  index(index: int) → Surface
    Parameters:

      index

    Raises:

      cairo.Error –

    Returns the surface at index `index`. The master surface is at index 0.

    Added in version 1.14.