Module fpdf.svg

Utilities to parse SVG graphics into fpdf.drawing objects.

The contents of this module are internal to fpdf2, and not part of the public API. They may change at any time without prior warning or any deprecation period, in non-backward-compatible ways.

Usage documentation at: https://py-pdf.github.io/fpdf2/SVG.html

Classes

class SVGImage (href: str,
x: numbers.Number,
y: numbers.Number,
width: numbers.Number,
height: numbers.Number,
svg_obj: SVGObject)
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

SVGImage(href, x, y, width, height, svg_obj)

Ancestors

  • builtins.tuple

Instance variables

var height : numbers.Number
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 4

var href : str
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 0

var svg_objSVGObject
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 5

var width : numbers.Number
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 3

var x : numbers.Number
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 1

var y : numbers.Number
Expand source code Browse git
class SVGImage(NamedTuple):
    href: str
    x: Number
    y: Number
    width: Number
    height: Number
    svg_obj: SVGObject

    def __deepcopy__(self, _memo):
        # Defining this method is required to avoid the .svg_obj reference to be cloned:
        return SVGImage(
            href=self.href,
            x=self.x,
            y=self.y,
            width=self.width,
            height=self.height,
            svg_obj=self.svg_obj,
        )

    @force_nodocument
    def render(self, _resource_registry, _style, last_item, initial_point):
        image_cache = self.svg_obj and self.svg_obj.image_cache
        if not image_cache:
            raise AssertionError(
                "fpdf2 bug - Cannot render a raster image without a SVGObject.image_cache"
            )

        # We lazy-import this function to circumvent a circular import problem:
        # pylint: disable=cyclic-import,import-outside-toplevel
        from .image_parsing import preload_image

        _, _, info = preload_image(image_cache, self.href)
        if isinstance(info, VectorImageInfo):
            LOGGER.warning(
                "Inserting .svg vector graphics in <image> tags is currently not supported (contributions are welcome to add support for it)"
            )
            return "", last_item, initial_point
        w, h = info.size_in_document_units(self.width, self.height)
        stream_content = stream_content_for_raster_image(
            info=info,
            x=self.x,
            y=self.y,
            w=w,
            h=h,
            keep_aspect_ratio=True,
        )
        return stream_content, last_item, initial_point

    @force_nodocument
    def render_debug(
        self, resource_registry, style, last_item, initial_point, debug_stream, _pfx
    ):
        stream_content, last_item, initial_point = self.render(
            resource_registry, style, last_item, initial_point
        )
        debug_stream.write(f"{self.href} rendered as: {stream_content}\n")
        return stream_content, last_item, initial_point

Alias for field number 2

class SVGObject (svg_text,
image_cache: ImageCache = None)
Expand source code Browse git
class SVGObject:
    """
    A representation of an SVG that has been converted to a PDF representation.
    """

    @classmethod
    def from_file(cls, filename, *args, encoding="utf-8", **kwargs):
        """
        Create an `SVGObject` from the contents of the file at `filename`.

        Args:
            filename (path-like): the path to a file containing SVG data.
            *args: forwarded directly to the SVGObject initializer. For subclass use.
            encoding (str): optional charset encoding to use when reading the file.
            **kwargs: forwarded directly to the SVGObject initializer. For subclass use.

        Returns:
            A converted `SVGObject`.
        """
        with open(filename, "r", encoding=encoding) as svgfile:
            return cls(svgfile.read(), *args, **kwargs)

    def __init__(self, svg_text, image_cache: ImageCache = None):
        self.image_cache = image_cache  # Needed to render images
        self.cross_references = {}
        self.css_class_styles = {}

        # disabling bandit rule as we use defusedxml:
        svg_tree = parse_xml_str(svg_text)  # nosec B314

        if svg_tree.tag not in xmlns_lookup("svg", "svg"):
            raise ValueError(f"root tag must be svg, not {svg_tree.tag}")

        self._collect_css_styles(svg_tree)
        self.extract_shape_info(svg_tree)
        self.convert_graphics(svg_tree)

    @force_nodocument
    def update_xref(self, key, referenced):
        if key:
            key = "#" + key if not key.startswith("#") else key
            self.cross_references[key] = referenced

    def _collect_css_styles(self, root_tag):
        for node in root_tag.iter():
            if node.tag in xmlns_lookup("svg", "style"):
                css_text = "".join(node.itertext() or [])
                for class_name, declarations in _extract_css_class_styles(css_text):
                    existing = self.css_class_styles.setdefault(class_name, {})
                    existing.update(declarations)

    def _style_map_for(self, tag):
        style_map = {}
        if self.css_class_styles:
            class_attr = tag.attrib.get("class")
            if class_attr:
                for class_name in class_attr.split():
                    class_styles = self.css_class_styles.get(class_name)
                    if class_styles:
                        style_map.update(class_styles)
        inline = html.parse_css_style(tag.attrib.get("style", ""))
        for key, value in inline.items():
            norm_value = _normalize_css_value(value)
            if norm_value is not None:
                style_map[key] = norm_value
            elif key in style_map:
                style_map.pop(key, None)
        inheritable_attrs = (
            "font-family",
            "font-size",
            "font-style",
            "font-weight",
            "text-anchor",
            "white-space",
        )
        for attr in inheritable_attrs:
            if attr in tag.attrib:
                norm_value = _normalize_css_value(tag.attrib.get(attr))
                if norm_value is not None:
                    style_map.setdefault(attr, norm_value)
        return style_map

    @force_nodocument
    def extract_shape_info(self, root_tag):
        """Collect shape info from the given SVG."""

        width = root_tag.get("width")
        height = root_tag.get("height")
        viewbox = root_tag.get("viewBox")
        # we don't fully support this, just check for its existence
        preserve_ar = root_tag.get("preserveAspectRatio", True)
        if preserve_ar == "none":
            self.preserve_ar = None
        else:
            self.preserve_ar = True

        self.width = None
        if width is not None:
            width.strip()
            if width.endswith("%"):
                self.width = Percent(width[:-1])
            else:
                self.width = resolve_length(width)

        self.height = None
        if height is not None:
            height.strip()
            if height.endswith("%"):
                self.height = Percent(height[:-1])
            else:
                self.height = resolve_length(height)

        if viewbox is None:
            self.viewbox = None
        else:
            viewbox = viewbox.strip()
            vx, vy, vw, vh = [float(num) for num in NUMBER_SPLIT.split(viewbox)]
            if (vw < 0) or (vh < 0):
                raise ValueError(f"invalid negative width/height in viewbox {viewbox}")

            self.viewbox = [vx, vy, vw, vh]

    @force_nodocument
    def convert_graphics(self, root_tag):
        """Convert the graphics contained in the SVG into the PDF representation."""
        base_group = GraphicsContext()
        base_group.style.stroke_width = None
        base_group.style.auto_close = False
        base_group.style.stroke_cap_style = "butt"

        self.build_group(root_tag, base_group)

        self.base_group = base_group

    def transform_to_page_viewport(self, pdf, align_viewbox=True):
        """
        Size the converted SVG paths to the page viewport.

        The SVG document size can be specified relative to the rendering viewport
        (e.g. width=50%). If the converted SVG sizes are relative units, then this
        computes the appropriate scale transform to size the SVG to the correct
        dimensions for a page in the current PDF document.

        If the SVG document size is specified in absolute units, then it is not scaled.

        Args:
            pdf (fpdf.fpdf.FPDF): the pdf to use the page size of.
            align_viewbox (bool): if True, mimic some of the SVG alignment rules if the
                viewbox aspect ratio does not match that of the viewport.

        Returns:
            The same thing as `SVGObject.transform_to_rect_viewport`.
        """

        return self.transform_to_rect_viewport(pdf.k, pdf.epw, pdf.eph, align_viewbox)

    def transform_to_rect_viewport(
        self, scale, width, height, align_viewbox=True, ignore_svg_top_attrs=False
    ):
        """
        Size the converted SVG paths to an arbitrarily sized viewport.

        The SVG document size can be specified relative to the rendering viewport
        (e.g. width=50%). If the converted SVG sizes are relative units, then this
        computes the appropriate scale transform to size the SVG to the correct
        dimensions for a page in the current PDF document.

        Args:
            scale (Number): the scale factor from document units to PDF points.
            width (Number): the width of the viewport to scale to in document units.
            height (Number): the height of the viewport to scale to in document units.
            align_viewbox (bool): if True, mimic some of the SVG alignment rules if the
                viewbox aspect ratio does not match that of the viewport.
            ignore_svg_top_attrs (bool): ignore <svg> top attributes like "width", "height"
                or "preserveAspectRatio" when figuring the image dimensions.
                Require width & height to be provided as parameters.

        Returns:
            A tuple of (width, height, `fpdf.drawing.GraphicsContext`), where width and
            height are the resolved width and height (they may be 0. If 0, the returned
            `fpdf.drawing.GraphicsContext` will be empty). The
            `fpdf.drawing.GraphicsContext` contains all of the paths that were
            converted from the SVG, scaled to the given viewport size.
        """

        if ignore_svg_top_attrs:
            vp_width = width
        elif isinstance(self.width, Percent):
            if not width:
                raise ValueError(
                    'SVG "width" is a percentage, hence a viewport width is required'
                )
            vp_width = self.width * width / 100
        else:
            vp_width = self.width or width

        if ignore_svg_top_attrs:
            vp_height = height
        elif isinstance(self.height, Percent):
            if not height:
                raise ValueError(
                    'SVG "height" is a percentage, hence a viewport height is required'
                )
            vp_height = self.height * height / 100
        else:
            vp_height = self.height or height

        if scale == 1:
            transform = Transform.identity()
        else:
            transform = Transform.scaling(1 / scale)

        if self.viewbox:
            vx, vy, vw, vh = self.viewbox

            if (vw == 0) or (vh == 0):
                return 0, 0, GraphicsContext()

            w_ratio = vp_width / vw
            h_ratio = vp_height / vh

            if not ignore_svg_top_attrs and self.preserve_ar and (w_ratio != h_ratio):
                w_ratio = h_ratio = min(w_ratio, h_ratio)

            transform = (
                transform
                @ Transform.translation(x=-vx, y=-vy)
                @ Transform.scaling(x=w_ratio, y=h_ratio)
            )

            if align_viewbox:
                transform = transform @ Transform.translation(
                    x=vp_width / 2 - (vw / 2) * w_ratio,
                    y=vp_height / 2 - (vh / 2) * h_ratio,
                )

        self.base_group.transform = transform

        return vp_width / scale, vp_height / scale, self.base_group

    def draw_to_page(self, pdf, x=None, y=None, debug_stream=None):
        """
        Directly draw the converted SVG to the given PDF's current page.

        The page viewport is used for sizing the SVG.

        Args:
            pdf (fpdf.fpdf.FPDF): the document to which the converted SVG is rendered.
            x (Number): abscissa of the converted SVG's top-left corner.
            y (Number): ordinate of the converted SVG's top-left corner.
            debug_stream (io.TextIO): the stream to which rendering debug info will be
                written.
        """
        self.image_cache = pdf.image_cache  # Needed to render images
        _, _, path = self.transform_to_page_viewport(pdf)

        old_x, old_y = pdf.x, pdf.y
        try:
            if x is not None and y is not None:
                pdf.set_xy(0, 0)
                path.transform = path.transform @ Transform.translation(x, y)

            pdf.draw_path(path, debug_stream)

        finally:
            pdf.set_xy(old_x, old_y)

    # defs paths are not drawn immediately but are added to xrefs and can be referenced
    # later to be drawn.
    @force_nodocument
    def handle_defs(self, defs):
        """Produce lookups for groups and paths inside the <defs> tag"""
        for child in defs:
            if child.tag in xmlns_lookup("svg", "g"):
                self.build_group(child)
            elif child.tag in xmlns_lookup("svg", "a"):
                # <a> tags aren't supported but we need to recurse into them to
                # render nested elements.
                LOGGER.warning(
                    "Ignoring unsupported SVG tag: <a> (contributions are welcome to add support for it)",
                )
                self.build_group(child)
            elif child.tag in xmlns_lookup("svg", "path"):
                self.build_path(child)
            elif child.tag in xmlns_lookup("svg", "image"):
                self.build_image(child)
            elif child.tag in shape_tags:
                self.build_shape(child)
            elif child.tag in xmlns_lookup("svg", "clipPath"):
                try:
                    clip_id = child.attrib["id"]
                except KeyError:
                    clip_id = None
                for child_ in child:
                    self.build_clipping_path(child_, clip_id)
            elif child.tag in xmlns_lookup("svg", "style"):
                # Styles handled globally during parsing
                continue
            else:
                LOGGER.warning(
                    "Ignoring unsupported SVG tag: <%s> (contributions are welcome to add support for it)",
                    without_ns(child.tag),
                )

    # this assumes xrefs only reference already-defined ids.
    # I don't know if this is required by the SVG spec.
    @force_nodocument
    def build_xref(self, xref):
        """Resolve a cross-reference to an already-seen SVG element by ID."""
        style_map = self._style_map_for(xref)
        pdf_group = GraphicsContext()
        apply_styles(pdf_group, xref, style_map)

        for candidate in xmlns_lookup("xlink", "href", "id"):
            try:
                ref = xref.attrib[candidate]
                break
            except KeyError:
                pass
        else:
            raise ValueError(f"use {xref} doesn't contain known xref attribute")

        try:
            pdf_group.add_item(self.cross_references[ref])
        except KeyError:
            raise ValueError(
                f"use {xref} references nonexistent ref id {ref}"
            ) from None

        if "x" in xref.attrib or "y" in xref.attrib:
            # Quoting the SVG spec - 5.6.2. Layout of re-used graphics:
            # > The x and y properties define an additional transformation translate(x,y)
            x, y = float(xref.attrib.get("x", 0)), float(xref.attrib.get("y", 0))
            pdf_group.transform = Transform.translation(x=x, y=y)
        # Note that we currently do not support "width" & "height" in <use>

        return pdf_group

    @force_nodocument
    def build_group(self, group, pdf_group=None, inherited_style=None):
        """Handle nested items within a group <g> tag."""
        local_style = self._style_map_for(group)
        merged_style = dict(inherited_style or {})
        merged_style.update(local_style)
        if pdf_group is None:
            pdf_group = GraphicsContext()
        apply_styles(pdf_group, group, merged_style)

        # handle defs before anything else
        for child in [
            child for child in group if child.tag in xmlns_lookup("svg", "defs")
        ]:
            self.handle_defs(child)

        for child in group:
            if child.tag in xmlns_lookup("svg", "defs"):
                self.handle_defs(child)
            elif child.tag in xmlns_lookup("svg", "style"):
                # Stylesheets already parsed globally.
                continue
            elif child.tag in xmlns_lookup("svg", "g"):
                pdf_group.add_item(self.build_group(child, None, merged_style), False)
            elif child.tag in xmlns_lookup("svg", "a"):
                # <a> tags aren't supported but we need to recurse into them to
                # render nested elements.
                LOGGER.warning(
                    "Ignoring unsupported SVG tag: <a> (contributions are welcome to add support for it)",
                )
                pdf_group.add_item(self.build_group(child, None, merged_style), False)
            elif child.tag in xmlns_lookup("svg", "path"):
                pdf_group.add_item(self.build_path(child), False)
            elif child.tag in shape_tags:
                pdf_group.add_item(self.build_shape(child), False)
            elif child.tag in xmlns_lookup("svg", "use"):
                pdf_group.add_item(self.build_xref(child), False)
            elif child.tag in xmlns_lookup("svg", "image"):
                pdf_group.add_item(self.build_image(child), False)
            elif child.tag in xmlns_lookup("svg", "text"):
                pdf_group.add_item(self.build_text(child, merged_style), False)
            else:
                LOGGER.warning(
                    "Ignoring unsupported SVG tag: <%s> (contributions are welcome to add support for it)",
                    without_ns(child.tag),
                )

        self.update_xref(group.attrib.get("id"), pdf_group)

        return pdf_group

    @force_nodocument
    def build_path(self, path):
        """Convert an SVG <path> tag into a PDF path object."""
        style_map = self._style_map_for(path)
        pdf_path = PaintedPath()
        apply_styles(pdf_path, path, style_map)
        self.apply_clipping_path(pdf_path, path, style_map)
        svg_path = path.attrib.get("d")
        if svg_path is not None:
            svg_path_converter(pdf_path, svg_path)
        self.update_xref(path.attrib.get("id"), pdf_path)
        return pdf_path

    @force_nodocument
    def build_shape(self, shape):
        """Convert an SVG shape tag into a PDF path object. Necessary to make xref (because ShapeBuilder doesn't have access to this object.)"""
        style_map = self._style_map_for(shape)
        shape_builder = getattr(ShapeBuilder, shape_tags[shape.tag])
        shape_path = shape_builder(shape)
        apply_styles(shape_path, shape, style_map)
        self.apply_clipping_path(shape_path, shape, style_map)
        self.update_xref(shape.attrib.get("id"), shape_path)
        return shape_path

    @force_nodocument
    def build_clipping_path(self, shape, clip_id):
        if shape.tag in shape_tags:
            style_map = self._style_map_for(shape)
            shape_builder = getattr(ShapeBuilder, shape_tags[shape.tag])
            clipping_path_shape = shape_builder(shape, True)
            apply_styles(clipping_path_shape, shape, style_map)
        elif shape.tag in xmlns_lookup("svg", "path"):
            style_map = self._style_map_for(shape)
            clipping_path_shape = PaintedPath()
            apply_styles(clipping_path_shape, shape, style_map)
            clipping_path_shape.paint_rule = PathPaintRule.DONT_PAINT
            svg_path = shape.attrib.get("d")
            if svg_path is not None:
                svg_path_converter(clipping_path_shape, svg_path)
        else:
            LOGGER.warning(
                "Ignoring unsupported <clipPath> child tag: <%s> (contributions are welcome to add support for it)",
                without_ns(shape.tag),
            )
            return
        self.update_xref(clip_id, clipping_path_shape)

    @force_nodocument
    def apply_clipping_path(self, stylable, svg_element, style_map=None):
        clip_value = None
        if style_map and "clip-path" in style_map:
            clip_value = style_map["clip-path"]
        if clip_value is None:
            clip_value = svg_element.attrib.get("clip-path")
        if clip_value:
            clipping_path_id = re.search(r"url\((\#\w+)\)", clip_value)
            stylable.clipping_path = self.cross_references[clipping_path_id[1]]

    @force_nodocument
    def build_image(self, image):
        href = None
        for key in xmlns_lookup("xlink", "href"):
            if key in image.attrib:
                href = image.attrib[key]
                break
        if not href:
            raise ValueError("<image> is missing a href attribute")
        width = float(image.attrib.get("width", 0))
        height = float(image.attrib.get("height", 0))
        if "preserveAspectRatio" in image.attrib:
            LOGGER.warning(
                '"preserveAspectRatio" defined on <image> is currently not supported (contributions are welcome to add support for it)'
            )
        if "style" in image.attrib:
            LOGGER.warning(
                '"style" defined on <image> is currently not supported (contributions are welcome to add support for it)'
            )
        if "transform" in image.attrib:
            LOGGER.warning(
                '"transform" defined on <image> is currently not supported (contributions are welcome to add support for it)'
            )
        # Note: at this moment, self.image_cache is not set yet:
        svg_image = SVGImage(
            href=href,
            x=float(image.attrib.get("x", "0")),
            y=float(image.attrib.get("y", "0")),
            width=width,
            height=height,
            svg_obj=self,
        )
        self.update_xref(image.attrib.get("id"), svg_image)
        return svg_image

    @force_nodocument
    def build_text(self, text_tag, inherited_style=None):
        """
        Convert <text> (and simple <tspan>) into a PaintedPath with Text runs.
        - Uses Text baseline at (x,y)
        - Honors x/y and dx/dy on <text> and direct child <tspan>
        - Flattens nested tspans; advanced per-character positioning is not implemented
        """
        local_style = self._style_map_for(text_tag)
        effective_style = dict(inherited_style or {})
        effective_style.update(local_style)
        path = PaintedPath()
        apply_styles(path, text_tag, local_style)
        self.apply_clipping_path(path, text_tag, effective_style)

        preserve_parent = _preserve_ws(effective_style, text_tag)

        base_family, base_emph, base_size, base_anchor = _parse_font_attrs(
            text_tag, effective_style
        )
        if base_family is None:
            base_family = "sans-serif"
        default_font_size = (
            base_size if base_size is not None else resolve_length("16px")
        )
        base_x, base_y, base_dx, base_dy = _parse_xy_delta(
            text_tag, effective_style, font_size=default_font_size
        )
        anchor_x = base_x + base_dx
        anchor_y = base_y + base_dy

        text_runs: list[TextRun] = []
        pending_dx = 0.0
        pending_dy = 0.0

        def _style_for_run(tag, style_map_for_tag):
            if tag is None or style_map_for_tag is None:
                return None
            context = GraphicsContext()
            apply_styles(context, tag, style_map_for_tag)
            context.style.auto_close = GraphicsStyle.INHERIT
            overrides = any(
                getattr(context.style, prop) is not GraphicsStyle.INHERIT
                for prop in GraphicsStyle.MERGE_PROPERTIES
            )
            if not overrides:
                return None
            return deepcopy(context.style)

        def _add_run(
            raw_text: str,
            family: Optional[str],
            emphasis: Optional[str],
            size: Optional[float],
            preserve: bool,
            dx_extra: float = 0.0,
            dy_extra: float = 0.0,
            abs_x: Optional[float] = None,
            abs_y: Optional[float] = None,
            style_tag=None,
            style_map_for_tag=None,
        ):
            nonlocal pending_dx, pending_dy
            raw = raw_text or ""
            collapsed = _collapse_ws(raw, preserve=preserve)
            if preserve:
                content = collapsed
            else:
                trimmed = collapsed.strip()
                if trimmed:
                    content = trimmed
                    if raw[:1].isspace():
                        content = " " + content
                    if raw[-1:].isspace():
                        content = content + " "
                else:
                    if (raw[:1].isspace() or raw[-1:].isspace()) and text_runs:
                        content = " "
                    else:
                        content = ""
            if not content:
                pending_dx += dx_extra
                pending_dy += dy_extra
                return

            run_size = size if size is not None else default_font_size
            run_family = family or base_family or "sans-serif"
            run_emphasis = (emphasis if emphasis is not None else base_emph) or ""
            run_dx = pending_dx + dx_extra
            run_dy = pending_dy + dy_extra
            pending_dx = 0.0
            pending_dy = 0.0
            run_style = _style_for_run(style_tag, style_map_for_tag)

            text_runs.append(
                TextRun(
                    text=content,
                    family=run_family,
                    emphasis=run_emphasis,
                    size=run_size,
                    dx=run_dx,
                    dy=run_dy,
                    abs_x=abs_x,
                    abs_y=abs_y,
                    run_style=run_style,
                )
            )

        # Leading text (before child <tspan>)
        _add_run(
            text_tag.text or "",
            base_family,
            base_emph,
            base_size,
            preserve=preserve_parent,
            style_tag=None,
            style_map_for_tag=None,
        )

        for child in text_tag:
            if child.tag in xmlns_lookup("svg", "tspan"):
                child_local_style = self._style_map_for(child)
                child_effective_style = dict(effective_style)
                child_effective_style.update(child_local_style)
                fam, emph, size, _anchor = _parse_font_attrs(
                    child, child_effective_style
                )
                run_font_size = size if size is not None else default_font_size
                x, y, dx, dy = _parse_xy_delta(
                    child, child_effective_style, font_size=run_font_size
                )

                child_preserve = _preserve_ws(child_effective_style, child)
                raw_itertext = "".join(child.itertext())
                tail_text = child.tail or ""
                if tail_text and raw_itertext.endswith(tail_text):
                    run_text = raw_itertext[: -len(tail_text)]
                else:
                    run_text = raw_itertext
                abs_x = None
                abs_y = None
                if "x" in child.attrib or (
                    child_local_style is not None and "x" in child_local_style
                ):
                    abs_x = x
                if "y" in child.attrib or (
                    child_local_style is not None and "y" in child_local_style
                ):
                    abs_y = y

                _add_run(
                    run_text,
                    fam,
                    emph,
                    size,
                    preserve=child_preserve,
                    dx_extra=dx,
                    dy_extra=dy,
                    abs_x=abs_x,
                    abs_y=abs_y,
                    style_tag=child,
                    style_map_for_tag=child_local_style,
                )

                # Text between tspans inherits parent style
                _add_run(
                    child.tail or "",
                    base_family,
                    base_emph,
                    base_size,
                    preserve=preserve_parent,
                    style_tag=None,
                    style_map_for_tag=None,
                )
            else:
                # other child tags are ignored (already logged elsewhere)
                pass

        if text_runs:
            path.add_path_element(
                Text(
                    x=anchor_x,
                    y=anchor_y,
                    text_runs=tuple(text_runs),
                    text_anchor=base_anchor,
                ),
                _copy=False,
            )

        self.update_xref(text_tag.attrib.get("id"), path)
        return path

A representation of an SVG that has been converted to a PDF representation.

Static methods

def from_file(filename, *args, encoding='utf-8', **kwargs)

Create an SVGObject from the contents of the file at filename.

Args

filename : path-like
the path to a file containing SVG data.
*args
forwarded directly to the SVGObject initializer. For subclass use.
encoding : str
optional charset encoding to use when reading the file.
**kwargs
forwarded directly to the SVGObject initializer. For subclass use.

Returns

A converted SVGObject.

Methods

def draw_to_page(self, pdf, x=None, y=None, debug_stream=None)
Expand source code Browse git
def draw_to_page(self, pdf, x=None, y=None, debug_stream=None):
    """
    Directly draw the converted SVG to the given PDF's current page.

    The page viewport is used for sizing the SVG.

    Args:
        pdf (fpdf.fpdf.FPDF): the document to which the converted SVG is rendered.
        x (Number): abscissa of the converted SVG's top-left corner.
        y (Number): ordinate of the converted SVG's top-left corner.
        debug_stream (io.TextIO): the stream to which rendering debug info will be
            written.
    """
    self.image_cache = pdf.image_cache  # Needed to render images
    _, _, path = self.transform_to_page_viewport(pdf)

    old_x, old_y = pdf.x, pdf.y
    try:
        if x is not None and y is not None:
            pdf.set_xy(0, 0)
            path.transform = path.transform @ Transform.translation(x, y)

        pdf.draw_path(path, debug_stream)

    finally:
        pdf.set_xy(old_x, old_y)

Directly draw the converted SVG to the given PDF's current page.

The page viewport is used for sizing the SVG.

Args

pdf : FPDF
the document to which the converted SVG is rendered.
x : Number
abscissa of the converted SVG's top-left corner.
y : Number
ordinate of the converted SVG's top-left corner.
debug_stream : io.TextIO
the stream to which rendering debug info will be written.
def transform_to_page_viewport(self, pdf, align_viewbox=True)
Expand source code Browse git
def transform_to_page_viewport(self, pdf, align_viewbox=True):
    """
    Size the converted SVG paths to the page viewport.

    The SVG document size can be specified relative to the rendering viewport
    (e.g. width=50%). If the converted SVG sizes are relative units, then this
    computes the appropriate scale transform to size the SVG to the correct
    dimensions for a page in the current PDF document.

    If the SVG document size is specified in absolute units, then it is not scaled.

    Args:
        pdf (fpdf.fpdf.FPDF): the pdf to use the page size of.
        align_viewbox (bool): if True, mimic some of the SVG alignment rules if the
            viewbox aspect ratio does not match that of the viewport.

    Returns:
        The same thing as `SVGObject.transform_to_rect_viewport`.
    """

    return self.transform_to_rect_viewport(pdf.k, pdf.epw, pdf.eph, align_viewbox)

Size the converted SVG paths to the page viewport.

The SVG document size can be specified relative to the rendering viewport (e.g. width=50%). If the converted SVG sizes are relative units, then this computes the appropriate scale transform to size the SVG to the correct dimensions for a page in the current PDF document.

If the SVG document size is specified in absolute units, then it is not scaled.

Args

pdf : FPDF
the pdf to use the page size of.
align_viewbox : bool
if True, mimic some of the SVG alignment rules if the viewbox aspect ratio does not match that of the viewport.

Returns

The same thing as SVGObject.transform_to_rect_viewport().

def transform_to_rect_viewport(self, scale, width, height, align_viewbox=True, ignore_svg_top_attrs=False)
Expand source code Browse git
def transform_to_rect_viewport(
    self, scale, width, height, align_viewbox=True, ignore_svg_top_attrs=False
):
    """
    Size the converted SVG paths to an arbitrarily sized viewport.

    The SVG document size can be specified relative to the rendering viewport
    (e.g. width=50%). If the converted SVG sizes are relative units, then this
    computes the appropriate scale transform to size the SVG to the correct
    dimensions for a page in the current PDF document.

    Args:
        scale (Number): the scale factor from document units to PDF points.
        width (Number): the width of the viewport to scale to in document units.
        height (Number): the height of the viewport to scale to in document units.
        align_viewbox (bool): if True, mimic some of the SVG alignment rules if the
            viewbox aspect ratio does not match that of the viewport.
        ignore_svg_top_attrs (bool): ignore <svg> top attributes like "width", "height"
            or "preserveAspectRatio" when figuring the image dimensions.
            Require width & height to be provided as parameters.

    Returns:
        A tuple of (width, height, `fpdf.drawing.GraphicsContext`), where width and
        height are the resolved width and height (they may be 0. If 0, the returned
        `fpdf.drawing.GraphicsContext` will be empty). The
        `fpdf.drawing.GraphicsContext` contains all of the paths that were
        converted from the SVG, scaled to the given viewport size.
    """

    if ignore_svg_top_attrs:
        vp_width = width
    elif isinstance(self.width, Percent):
        if not width:
            raise ValueError(
                'SVG "width" is a percentage, hence a viewport width is required'
            )
        vp_width = self.width * width / 100
    else:
        vp_width = self.width or width

    if ignore_svg_top_attrs:
        vp_height = height
    elif isinstance(self.height, Percent):
        if not height:
            raise ValueError(
                'SVG "height" is a percentage, hence a viewport height is required'
            )
        vp_height = self.height * height / 100
    else:
        vp_height = self.height or height

    if scale == 1:
        transform = Transform.identity()
    else:
        transform = Transform.scaling(1 / scale)

    if self.viewbox:
        vx, vy, vw, vh = self.viewbox

        if (vw == 0) or (vh == 0):
            return 0, 0, GraphicsContext()

        w_ratio = vp_width / vw
        h_ratio = vp_height / vh

        if not ignore_svg_top_attrs and self.preserve_ar and (w_ratio != h_ratio):
            w_ratio = h_ratio = min(w_ratio, h_ratio)

        transform = (
            transform
            @ Transform.translation(x=-vx, y=-vy)
            @ Transform.scaling(x=w_ratio, y=h_ratio)
        )

        if align_viewbox:
            transform = transform @ Transform.translation(
                x=vp_width / 2 - (vw / 2) * w_ratio,
                y=vp_height / 2 - (vh / 2) * h_ratio,
            )

    self.base_group.transform = transform

    return vp_width / scale, vp_height / scale, self.base_group

Size the converted SVG paths to an arbitrarily sized viewport.

The SVG document size can be specified relative to the rendering viewport (e.g. width=50%). If the converted SVG sizes are relative units, then this computes the appropriate scale transform to size the SVG to the correct dimensions for a page in the current PDF document.

Args

scale : Number
the scale factor from document units to PDF points.
width : Number
the width of the viewport to scale to in document units.
height : Number
the height of the viewport to scale to in document units.
align_viewbox : bool
if True, mimic some of the SVG alignment rules if the viewbox aspect ratio does not match that of the viewport.
ignore_svg_top_attrs : bool
ignore top attributes like "width", "height" or "preserveAspectRatio" when figuring the image dimensions. Require width & height to be provided as parameters.

Returns

A tuple of (width, height, GraphicsContext), where width and height are the resolved width and height (they may be 0. If 0, the returned GraphicsContext will be empty). The GraphicsContext contains all of the paths that were converted from the SVG, scaled to the given viewport size.