Search code examples
python-3.xsvg

Python - Merging 2 SVG elelments into one SVG element


I am loading two SVGs which should have:

  1. a starting point (x %, y %) from the bottom left corner
  2. total width and height percentage.

I would like to merge them into one SVG having the first SVG and the second SVG positioned in the requested position.

I tried to use 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))
???

Thanks


Solution

  • the solution is to create a wrapper drawing:

    import io
    from svglib.svglib import svg2rlg
    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 = svg2rlg(io.StringIO(svg_1_content))
    svg_2_element = svg2rlg(io.StringIO(svg_2_content))
    width = 100
    height = 100
    svg_element = 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)
    

    the svg 1 and 2 should be scaled into the wanted size - this is just a simple example

    after the 2 objects are inside the drawing - to create a svg from it you can use the following code:

    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)