Last active
September 22, 2020 20:27
-
-
Save jrief/25962a9194ec1c6c3c590bf8977fd0ff to your computer and use it in GitHub Desktop.
crop_svg.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from reportlab.graphics import renderSVG | |
from svglib.svglib import svg2rlg | |
""" | |
The input file circle.svg contains this content: | |
<svg viewBox="0 0 300 300"> | |
<circle r="100" fill="red" transform="translate(150,150)"></circle> | |
<rect x="-25" y="-25" width="50" height="50" fill="green" transform="translate(150,150)"></rect> | |
</svg> | |
""" | |
drawing = svg2rlg("circle.svg") | |
left, bottom, right, top = drawing.getBounds() | |
canvas = renderSVG.SVGCanvas() | |
renderSVG.draw(drawing, canvas) | |
clipRect = next(iter(canvas.svg.getElementsByTagName('clipPath'))).firstChild | |
clipRect.setAttribute('x', '66') # from | |
clipRect.setAttribute('y', '199') # your | |
clipRect.setAttribute('width', '189') # cropping | |
clipRect.setAttribute('height', '222') # algorithm | |
canvas.save('circle_cropped.svg') | |
""" | |
This creates a file circle_cropped.svg containing a clipping rectangle: | |
<?xml version="1.0" encoding="utf-8"?> | |
<!DOCTYPE svg | |
PUBLIC '-//W3C//DTD SVG 1.0//EN' | |
'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'> | |
<svg fill-rule="evenodd" height="400.0" preserveAspectRatio="xMinYMin meet" version="1.0" viewBox="0 0 400 400" width="400.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> | |
<title>...</title> | |
<desc>...</desc> | |
<clipPath id="clip"> | |
<rect height="400.0" width="400.0" x="0" y="0"/> | |
</clipPath> | |
<g id="group" style="clip-path: url(#clip)" transform="scale(1,-1) translate(0,-400)"> | |
<g transform=""> | |
<g transform=" matrix(1.000000,0.000000,0.000000,-1.000000,0.000000,400.000000)"> | |
<g transform=" matrix(1.000000,0.000000,0.000000,1.000000,150.000000,150.000000)"> | |
<circle cx="0.0" cy="0.0" r="100.0" style="stroke: none; stroke-linecap: butt; stroke-width: 1; fill: rgb(100%,0%,0%);"/> | |
</g> | |
<g transform=" matrix(1.000000,0.000000,0.000000,1.000000,150.000000,150.000000)"> | |
<rect height="50.0" style="stroke: none; stroke-linecap: butt; stroke-width: 1; fill: rgb(0%,50%,0%);" width="50.0" x="-25.0" y="-25.0"/> | |
</g> | |
</g> | |
</g> | |
</g> | |
</svg> | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment