首页 > 解决方案 > Python - 将 2 个 SVG 元素合并为一个 SVG 元素

问题描述

我正在加载两个应该具有的 SVG:

  1. 从左下角的起点 (x %, y %)
  2. 总宽度和高度百分比。

我想将它们合并到一个 SVG 中,其中第一个 SVG 和第二个 SVG 位于请求的位置。

我试着用svglib

class Position:
    def __init__(self, x_start_position: float, y_start_position: float, height: float, width: float):   
        self.x_start_position = x_start_position
        self.y_start_position = y_start_position
        self.height = height
        self.width = width


drawing_1_position = Position(0, 0, 100, 100) 
drawing_2_position = Position(20, 20, 80, 80)
# the first drawing should be taken with it's full size and start from the bottom left corner 
# the second drawing should be taken with 80% of it's height and 80% of it's width starting 20% from the bottom left corner for it's height and length

drawing_1 = svglib.svg2rlg(io.StringIO(svg_1))
drawing_2 = svglib.svg2rlg(io.StringIO(svg_2))
???

谢谢

标签: python-3.xsvg

解决方案


解决方案是创建一个包装图:

import io
import svglib
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.renderSVG import SVGCanvas, draw

with open("sample1.svg") as fp:
    svg_1_content = fp.read()

with open("sample2.svg") as fp:
    svg_2_content = fp.read()
svg_1_element = svglib.svg2rlg(io.StringIO(svg_1_content))
svg_2_element = svglib.svg2rlg(io.StringIO(svg_2_content))
width = 100
height = 100
svg_element = svglib.svg2rlg(io.StringIO(background_content))
d = Drawing(width, height) # setting the width and height
svg_1_element.scale(width / svg_1_element.width, height / svg_2_element.height)
svg_2_element.scale(width / svg_1_element.width, height / svg_2_element.height)
d.add(svg_1_element)
d.add(svg_2_element)

svg 1 和 2 应该缩放到想要的大小 - 这只是一个简单的例子

在 2 个对象位于绘图内之后 - 要从中创建 svg,您可以使用以下代码:

s = getStringIO()
c = SVGCanvas((d.width, d.height))
draw(d, c, 0, 0)
c.save(s)
print(s.getvalue()) # here is the svg output (that can be shown inside a html web page)

推荐阅读