Skip to content

svg

svg

Image header parser for SVG images.

SVG is XML, so there is no fixed-offset magic number to match and no binary header to unpack. Size comes from the width and height attributes of the root <svg> element, which are CSS lengths and may carry any of the usual units, or — when those are absent or given as percentages, which is common for icons meant to scale — from the viewBox.

One SVG user unit is one CSS pixel, 1/96 inch, which is why the resolution reported here is 96 rather than the 72 the resolution-free raster formats assume.

Svg

Svg(
    px_width: int,
    px_height: int,
    horz_dpi: int,
    vert_dpi: int,
    orientation: int = 1,
)

Bases: BaseImageHeader

Image header parser for SVG images.

Source code in src/docx/image/image.py
def __init__(
    self,
    px_width: int,
    px_height: int,
    horz_dpi: int,
    vert_dpi: int,
    orientation: int = 1,
):
    self._px_width = px_width
    self._px_height = px_height
    self._horz_dpi = horz_dpi
    self._vert_dpi = vert_dpi
    self._orientation = orientation

content_type property

content_type

MIME content type for this image, unconditionally image/svg+xml for SVG images.

default_ext property

default_ext

Default filename extension, always 'svg' for SVG images.

sniff classmethod

sniff(header: bytes) -> bool

True when header looks like the start of an SVG document.

SVG has no magic number, so detection is by finding an <svg root element ahead of any other element. Matched against the leading bytes of the file rather than at a fixed offset, because an XML declaration, a DOCTYPE and comments may all precede the root.

Source code in src/docx/image/svg.py
@classmethod
def sniff(cls, header: bytes) -> bool:
    """True when `header` looks like the start of an SVG document.

    SVG has no magic number, so detection is by finding an `<svg` root element ahead
    of any other element. Matched against the leading bytes of the file rather than
    at a fixed offset, because an XML declaration, a DOCTYPE and comments may all
    precede the root.
    """
    prefix = header[:_SNIFF_LENGTH]
    match = _SVG_ROOT_RE.search(prefix)
    if match is None:
        return False
    # -- reject a document whose root is something else that merely contains an
    # -- embedded `<svg>`, such as XHTML --
    first_element = re.search(rb"<[A-Za-z]", prefix)
    return first_element is not None and first_element.start() == match.start()

from_stream classmethod

from_stream(stream)

Return an Svg instance with header properties parsed from stream.

Source code in src/docx/image/svg.py
@classmethod
def from_stream(cls, stream):
    """Return an |Svg| instance with header properties parsed from `stream`."""
    root = cls._parse_root(stream)
    inch_width, inch_height = cls._extents_in_inches(root)
    px_width = int(round(inch_width * _SVG_DPI))
    px_height = int(round(inch_height * _SVG_DPI))
    return cls(px_width, px_height, _SVG_DPI, _SVG_DPI)