├── requirements.txt ├── .gitignore ├── example.py ├── setup.py ├── examples ├── translations.svg ├── styles.svg └── paths.svg ├── Javascript ├── main.css ├── main.html ├── optimiser_tests.js └── svg-optimiser.js ├── readme.md ├── LICENSE └── cleanSVG.py /requirements.txt: -------------------------------------------------------------------------------- 1 | lxml==3.2.0 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | compiled files # 2 | ################## 3 | *.pyc 4 | venv 5 | 6 | # OS generated files # 7 | *~ 8 | 9 | # Examples 10 | /examples/* 11 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from cleanSVG import CleanSVG 2 | import os 3 | 4 | input_file = os.path.join("examples", "paths_test.svg") 5 | output_file = "cleaned-test.svg" 6 | 7 | svg = CleanSVG(input_file) 8 | svg.removeAttribute('id') 9 | svg.setDecimalPlaces(1) 10 | svg.extractStyles() 11 | svg.removeElement('title') 12 | svg.removeElement('desc') 13 | svg.removeElement('defs') 14 | svg.removeComments() 15 | svg.applyTransforms() 16 | svg.write(output_file) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | 6 | setup( 7 | name='SVG-Optimizer', 8 | version='0.1', 9 | description='Python program to clean up SVG files, particularly those created by Inkscape or Illustrator', 10 | author='Peter Collingridge', 11 | author_email='peter.collingridge@gmail.com', 12 | url='https://github.com/petercollingridge/SVG-Optimiser', 13 | py_modules=['cleanSVG'], 14 | install_requires=open('requirements.txt').readlines(), 15 | ) 16 | -------------------------------------------------------------------------------- /examples/translations.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /examples/styles.svg: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | 13 | 14 | 17 | 18 | 21 | 22 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Javascript/main.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Verdana, helvetica, sans-serif; 3 | } 4 | 5 | h1 { 6 | width: 880px; 7 | font-size: 36px; 8 | border-bottom: 1px solid #aaa; 9 | padding-left: 20px; 10 | padding-bottom: 2px; 11 | margin-top: 12px; 12 | margin-bottom: 0; 13 | color: #111; 14 | text-shadow: 1px 1px 0px #e1e1e8; 15 | } 16 | 17 | h2 { 18 | font-weight: normal; 19 | font-size: 20px; 20 | padding-left: 8px; 21 | padding-bottom: 2px; 22 | color: #222; 23 | border-bottom: 1px solid #888; 24 | margin-top: 24px; 25 | margin-bottom: 5px; 26 | } 27 | 28 | h3 { 29 | font-size: 13px; 30 | padding-left: 8px; 31 | padding-right: 40px; 32 | color: #222; 33 | margin-top: 6px; 34 | margin-bottom: 2px; 35 | clear: both; 36 | } 37 | 38 | p { 39 | margin: 5px; 40 | line-height: 19px; 41 | text-align: justify; 42 | } 43 | 44 | textarea { 45 | margin-bottom: 0; 46 | outline: none; 47 | } 48 | 49 | a:link { 50 | color: #86d62a; 51 | text-decoration: none; 52 | } 53 | 54 | a:visited { 55 | color: #86d62a; 56 | } 57 | 58 | a:hover { 59 | text-decoration: underline; 60 | } 61 | 62 | .page-content { 63 | font-size: 13px; 64 | width: 800px; 65 | padding-left: 40px; 66 | } 67 | 68 | .input-output-box { 69 | font-family: Fixed, "Courier New", monospace; 70 | border: 1px #565752 solid; 71 | padding: 6px 4px 6px 10px; 72 | } 73 | 74 | #output-svg { 75 | height: 50px; 76 | overflow: auto; 77 | resize: both; 78 | } 79 | 80 | #apply-button { 81 | font-size: 14px; 82 | padding: 4px 10px 4px 10px; 83 | } 84 | 85 | #error-message { 86 | color: red; 87 | } 88 | 89 | .implementation-list { 90 | float: left; 91 | display: inline-block; 92 | vertical-align: top; 93 | } 94 | 95 | .implementation-list>ul { 96 | font-style: italic; 97 | list-style-type: none; 98 | padding-left: 16px; 99 | margin-top: 4px; 100 | margin-bottom: 4px; 101 | } 102 | 103 | .implementation-list li { 104 | padding: 2px 6px 2px 2px; 105 | } 106 | 107 | .implemented:hover { 108 | cursor: pointer; 109 | background: #ddd; 110 | } 111 | 112 | .not-implemented { 113 | color: #888; 114 | } 115 | 116 | .text-button { 117 | color: #2048a8; 118 | font-weight: bold; 119 | cursor: pointer; 120 | padding: 8px 4px 4px 10px; 121 | clear: both; 122 | } 123 | 124 | .footer { 125 | font-size: 10px; 126 | padding-top: 16px; 127 | padding-left: 20px; 128 | padding-bottom: 1px; 129 | clear: both; 130 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | Python program to clean up SVG files, particularly those created by Inkscape or Illustrator 2 | 3 | 4 | 5 | # --- Current Functionality --- 6 | 7 | ## Remove attributes 8 | Remove attributes with a given name, e.g. remove 'id' attributes, which often aren't used. 9 | 10 | ## Remove comments 11 | Removes all comments. 12 | 13 | ## Remove elements 14 | Remove elements by their tag name. 15 | 16 | ## Remove namespaces 17 | Remove all attributes associated with a given namespace, e.g. remove 'sodipodi' attributes created by Inkscape. 18 | 19 | ## Remove redundant groups 20 | Move child elements outdside of group with no attributes, then delete group. 21 | 22 | ## Set decimal places 23 | Rewrite attributes to a given number of decimal places. 24 | Strip out unnecessary trailing zeros. 25 | 26 | * Attributes 27 | - x, y, x1, y2, x2, y2 28 | - cx, cy 29 | - r, rx, ry 30 | - width, height 31 | - points 32 | - d 33 | 34 | ## Apply transformations 35 | Applies transformations to elements so the attribute can be removed. 36 | 37 | * Translation 38 | - In the form 39 | - comma: (12,34) 40 | - space(s): (12 34) 41 | - comma and space(s): (12, 34), (12 ,34), (12 , 34) 42 | - decimal: (1.2, 3.4) 43 | - negative: (-1.2, -3.4) 44 | 45 | - Shapes 46 | - line 47 | - rect 48 | - circle, ellipse 49 | - polyline, polygon 50 | - path (not fully tested) 51 | - g (not fully tested) 52 | 53 | * Scale 54 | - Shapes 55 | - path 56 | - rect 57 | 58 | ## CSS stlying 59 | Convert individual style attributes to CSS styling. 60 | Remove default styles. 61 | 62 | # --- To Do --- 63 | 64 | ## Remove namespaces 65 | Remove xml namespace if possible 66 | 67 | ## Groups 68 | Remove unnecessary groups 69 | Remove unnecessary text groups 70 | Add groups in make styling and transforms more efficient 71 | 72 | ## Transformations 73 | 74 | * Translation 75 | - In the form 76 | - single: (12) 77 | 78 | - Shapes 79 | - text 80 | - tspan 81 | 82 | * Rotation 83 | - Shapes 84 | - path 85 | - polyline/polygon 86 | - line 87 | - circle 88 | - rect -> polygon/path? 89 | 90 | * Scale 91 | - Shapes 92 | - polyline/polygon 93 | - line 94 | - circle -> ellipse? 95 | 96 | * SkewX and SkewY 97 | - Shapes 98 | - line 99 | - path 100 | - polyline/polygon 101 | - rect -> polygon/path? 102 | - circle -> path arc? 103 | 104 | * Matrix 105 | - Shapes 106 | - line 107 | - path 108 | - polyline/polygon 109 | - rect -> polygon/path? 110 | 111 | ## CSS styling 112 | Need to check whether style element already exists and whether class names already exist. 113 | Ideally find most efficient way to class elements for styling. 114 | 115 | ## License 116 | 117 | 118 | -------------------------------------------------------------------------------- /examples/paths.svg: -------------------------------------------------------------------------------- 1 | 5 | 6 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /Javascript/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Simplify an SVG 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Apply SVG Transformations

15 |
16 |

See the result of applying a transformation to SVG elements. Click on the currently implemented items to show an example.

17 | 18 |

Input

19 | 23 |
24 | 28 | 29 |
30 |
31 | 32 |

Output

33 |
34 | 35 |
36 |

Currently implemented

37 |

These are the elements and transformations that are currently implemented. 38 | Click on an example to add it to the input. 39 | Note that not all transformations can be applied to every element. 40 | For example, scaling a circle differently in two dimensions will not result in a circle so has not been implemented. 41 | At present, only one transformation can be applied at a time. 42 | You can apply it to multiple SVG elements as long as they are not nested (so no elements). 43 | Scaling an element will not effect its stroke width. 44 |

45 | 46 |
47 |
48 |

Elements

49 |
    50 |
  • Rect
  • 51 |
  • Circle
  • 52 |
  • Ellipse
  • 53 |
  • Line
  • 54 |
  • Polyline
  • 55 |
  • Polygon
  • 56 |
57 |
58 |
59 |

Path sections

60 |
    61 |
  • M/m, L/l, Z/z
  • 62 |
  • H/h, V/v
  • 63 |
  • Q/q, T/t
  • 64 |
  • C/c, S/s
  • 65 |
  • A/a
  • 66 |
67 |
68 |
69 |

Transformations

70 |
    71 |
  • 1D Translation
  • 72 |
  • 2D Translation
  • 73 |
  • 1D Scale
  • 74 |
  • 2D Scale
  • 75 |
  • Rotation
  • 76 |
  • Skew X
  • 77 |
  • Skew Y
  • 78 |
79 |
80 |
81 |

Matrix transformations

82 |
    83 |
  • Translation matrix
  • 84 |
  • Scaling matrix
  • 85 |
  • Translate and scale matrix
  • 86 |
  • Rotation matrix
  • 87 |
  • Skew X matrix
  • 88 |
  • Skew Y matrix
  • 89 |
  • General matrix
  • 90 |
91 |
92 |
93 |
94 |
Run Tests
95 |
96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /Javascript/optimiser_tests.js: -------------------------------------------------------------------------------- 1 | function TransformTester() { 2 | // Object to convert transformations into strings so they can be easily tested. 3 | this.transform_str = "undefined"; 4 | 5 | this.translate = function(dx, dy) { 6 | this.transform_str = "translate(" + dx + " " + dy + ")"; 7 | } 8 | 9 | this.scale = function(sx, sy) { 10 | this.transform_str = "scale(" + sx + " " + sy + ")"; 11 | } 12 | 13 | this.matrix = function(a, b, c, d, e, f) { 14 | this.transform_str = "matrix(" + a + " " + b + " " + c +" " + d +" " + e +" " + f + ")"; 15 | } 16 | } 17 | 18 | var transformation_parse_tests = [ 19 | ['none', ''], 20 | ['translate(twelve)', ''], 21 | ['translate(one 2)', ''], 22 | ['translate(12)', 'translate(12 0)'], 23 | ['translate( 12)', 'translate(12 0)'], 24 | ['translate(12 )', 'translate(12 0)'], 25 | ['translate( 12 )', 'translate(12 0)'], 26 | ['translate ( 12 ) ', 'translate(12 0)'], 27 | ['translate(12 34)', 'translate(12 34)'], 28 | ['translate(12 34 )', 'translate(12 34)'], 29 | ['translate(12,34)', 'translate(12 34)'], 30 | ['translate(12, 34)', 'translate(12 34)'], 31 | ['translate(12 ,34)', 'translate(12 34)'], 32 | ['translate( 12 , 34 )', 'translate(12 34)'], 33 | ['translate( -12 )', 'translate(-12 0)'], 34 | ['translate( +12.0 )', 'translate(12 0)'], 35 | ['translate( 12.0 )', 'translate(12 0)'], 36 | ['translate( 12. )', 'translate(12 0)'], 37 | ['translate( 12.2 )', 'translate(12.2 0)'], 38 | ['translate( 12.02 )', 'translate(12.02 0)'], 39 | ['translate( -12.002 )', 'translate(-12.002 0)'], 40 | ['translate( .002 )', 'translate(0.002 0)'], 41 | ['translate( -.002 )', 'translate(-0.002 0)'], 42 | ['translate( -.002 0.03 )', 'translate(-0.002 0.03)'], 43 | ['translate( -9.9e-1 )', 'translate(-0.99 0)'], 44 | ['scale( 0.2 )', 'scale(0.2 0.2)'], 45 | ['scale( 0.2 -1.2 )', 'scale(0.2 -1.2)'], 46 | ['scale( -10.2, 1.2 )', 'scale(-10.2 1.2)'], 47 | ['matrix( 1.5 -2 3 0.4 -5.5 6 7.6)', ''], 48 | ['matrix( 1.5 -2 3 0.4 -5.5 6 )', 'matrix(1.5 -2 3 0.4 -5.5 6)'], 49 | ['matrix( 1.1 -2.2 -3.3 , 4.4, -5.5 6 )', 'matrix(1.1 -2.2 -3.3 4.4 -5.5 6)'], 50 | ]; 51 | 52 | var test_transformations = { 53 | 'null transform' : 'nonsense string', 54 | '1D translate' : 'translate(-12.5)', 55 | '2D translate' : 'translate(12.5 -4)', 56 | '1D scale' : 'scale(-1.5)', 57 | '2D scale' : 'scale(1.5 -2)', 58 | 'translate matrix': 'matrix(1 0 0 1 12.5 -4)', 59 | 'scale matrix': 'matrix(1.5 0 0 -2 0 0)', 60 | 'translate and scale matrix': 'matrix(1.5 0 0 -2 12.5 -4)', 61 | 'matrix transformation': 'matrix(1.5 -2 3 0.4 -5.5 6)' 62 | }; 63 | 64 | var SVG_elements = { 65 | rect: '', 66 | rounded_rect: '', 67 | circle: '', 68 | ellipse: '', 69 | line: '', 70 | polyline: '', 71 | polygon: '', 72 | messy_polyline: '', 73 | path_ML: '', 74 | path_MLl: '', 75 | path_HhVv: '', 76 | path_QqTt: '', 77 | path_CcSs: '', 78 | xml_style: '', 79 | with_style: '', 80 | missing_attributes: '', 81 | no_attributes: '', 82 | additional_attributes: '', 83 | namespaced_attribute: '' 84 | }; 85 | 86 | var test_cases = [ 87 | ['null transform', 'rect', 'null'], 88 | ['null transform', 'circle', 'null'], 89 | ['null transform', 'ellipse', 'null'], 90 | ['null transform', 'line', 'null'], 91 | ['null transform', 'polyline', 'null'], 92 | ['null transform', 'polygon', 'null'], 93 | ['null transform', 'path_ML', 'null'], 94 | ['1D translate', 'rect', {x: -2.5, y: 20, width: 15, height: 25}], 95 | ['1D translate', 'circle', {cx: -2.5, cy: 20, r: 3}], 96 | ['1D translate', 'ellipse', {cx: -2.5, cy: 20, rx: 4, ry: 5}], 97 | ['1D translate', 'line', {x1: -2.5, y1: 20, x2: 2.5, y2: 35}], 98 | ['1D translate', 'polyline', {points: "-2.5,20 12.5,35 -7.5,35"}], 99 | ['1D translate', 'polygon', {points: "-2.5,20 12.5,35 -7.5,35"}], 100 | ['1D translate', 'path_ML', {d: "M-2.5 -20 L-37.5 -30.05 -42.5 -25 L-6.5 -3 z"}], 101 | ['2D translate', 'rect', {x: 22.5, y: 16, width: 15, height: 25}], 102 | ['2D translate', 'circle', {cx: 22.5, cy: 16, r: 3}], 103 | ['2D translate', 'ellipse', {cx: 22.5, cy: 16, rx: 4, ry: 5}], 104 | ['2D translate', 'line', {x1: 22.5, y1: 16, x2: 27.5, y2: 31}], 105 | ['2D translate', 'polyline', {points: "22.5,16 37.5,31 17.5,31"}], 106 | ['2D translate', 'polygon', {points: "22.5,16 37.5,31 17.5,31"}], 107 | ['2D translate', 'path_ML', {d: "M22.5 -24 L-12.5 -34.05 -17.5 -29 L18.5 -7 z"}], 108 | ['1D scale', 'rect', {x: -37.5, y: -67.5, width: 22.5, height: 37.5}], 109 | ['1D scale', 'circle', {cx: -15, cy: -30, r: 4.5}], 110 | ['1D scale', 'ellipse', {cx: -15, cy: -30, rx: 6, ry: 7.5}], 111 | ['1D scale', 'line', {x1: -15, y1: -30, x2: -22.5, y2: -52.5}], 112 | ['1D scale', 'polyline', {points: "-15,-30 -37.5,-52.5 -7.5,-52.5"}], 113 | ['1D scale', 'polygon', {points: "-15,-30 -37.5,-52.5 -7.5,-52.5"}], 114 | ['2D scale', 'rect', {x: 15, y: -90, width: 22.5, height: 50}], 115 | ['2D scale', 'circle', 'null'], 116 | ['2D scale', 'ellipse', {cx: 15, cy: -40, rx: 6, ry: 10}], 117 | ['2D scale', 'line', {x1: 15, y1: -40, x2: 22.5, y2: -70}], 118 | ['2D scale', 'polyline', {points: "15,-40 37.5,-70 7.5,-70"}], 119 | ['2D scale', 'polygon', {points: "15,-40 37.5,-70 7.5,-70"}], 120 | ['translate matrix', 'rect', {x: 22.5, y: 16, width: 15, height: 25}], 121 | ['translate matrix', 'circle', {cx: 22.5, cy: 16, r: 3}], 122 | ['translate matrix', 'ellipse', {cx: 22.5, cy: 16, rx: 4, ry: 5}], 123 | ['translate matrix', 'line', {x1: 22.5, y1: 16, x2: 27.5, y2: 31}], 124 | ['translate matrix', 'polyline', {points: "22.5,16 37.5,31 17.5,31"}], 125 | ['translate matrix', 'polygon', {points: "22.5,16 37.5,31 17.5,31"}], 126 | ['scale matrix', 'rect', {x: 15, y: -90, width: 22.5, height: 50}], 127 | ['scale matrix', 'circle', 'null'], 128 | ['scale matrix', 'ellipse', {cx: 15, cy: -40, rx: 6, ry: 10}], 129 | ['scale matrix', 'line', {x1: 15, y1: -40, x2: 22.5, y2: -70}], 130 | ['scale matrix', 'polyline', {points: "15,-40 37.5,-70 7.5,-70"}], 131 | ['scale matrix', 'polygon', {points: "15,-40 37.5,-70 7.5,-70"}], 132 | ['translate and scale matrix', 'rect', {x: 27.5, y: -94, width: 22.5, height: 50}], 133 | ['translate and scale matrix', 'circle', {cx: 22.5, cy: 16, r: 3}], // Doesn't scale anything 134 | ['translate and scale matrix', 'ellipse', {cx: 27.5, cy: -44, rx: 6, ry: 10}], 135 | ['translate and scale matrix', 'line', {x1: 27.5, y1: -44, x2: 35, y2: -74}], 136 | ['translate and scale matrix', 'polyline', {points: "27.5,-44 50,-74 20,-74"}], 137 | ['translate and scale matrix', 'polygon', {points: "27.5,-44 50,-74 20,-74"}], 138 | ['matrix transformation', 'rect', 'null'], 139 | ['matrix transformation', 'circle', 'null'], 140 | ['matrix transformation', 'ellipse', 'null'], 141 | ['matrix transformation', 'line', {x1: 69.5, y1: -6, x2: 122, y2: -10}], 142 | ['matrix transformation', 'polyline', {points: "69.5,-6 137,-30 107,10"}], 143 | ['matrix transformation', 'polygon', {points: "69.5,-6 137,-30 107,10"}], 144 | ]; 145 | 146 | var testElementParsing = function() { 147 | // Test ability to parse SVG elements 148 | // Read then write SVG string and test whether the input and output are the same 149 | 150 | console.log("Test element parsing"); 151 | for (var element in SVG_elements) { 152 | var SVG_string = SVG_elements[element] 153 | var element_object = parseSVGString(SVG_string); 154 | 155 | if (!element_object) { 156 | console.log (" - failed to parse " + element); 157 | } else { 158 | if (element_object[0].write() != SVG_string){ 159 | console.log (" - " + SVG_string + " parsed as " + element_object[0].write()); 160 | } 161 | } 162 | } 163 | } 164 | 165 | var testTransformationParsing = function() { 166 | // Test ability to parse transformations 167 | 168 | console.log("Test transformation parsing"); 169 | var transform_tester = new TransformTester(); 170 | var passed_count = transformation_parse_tests.length; 171 | 172 | for (var t in transformation_parse_tests) { 173 | var transform = transformation_parse_tests[t][0]; 174 | var result = transformation_parse_tests[t][1]; 175 | var transform_function = parseTransformString(transform); 176 | 177 | if (transform_function) { 178 | transform_function(transform_tester); 179 | if (transform_tester.transform_str != result) { 180 | console.log(" - " + transform + " parsed as " + transform_tester.transform_str); 181 | passed_count--; 182 | } 183 | } else { 184 | if (result) { 185 | console.log(" - failed to parse " + transform); 186 | passed_count--; 187 | } 188 | } 189 | } 190 | console.log(" * Passed " + passed_count + " of " + transformation_parse_tests.length); 191 | } 192 | 193 | var testTransformations = function() { 194 | // Test running transformations on elements 195 | 196 | console.log("Test transformations"); 197 | var passed_count = 0; 198 | 199 | for (var t in test_cases) { 200 | var transformation_str = test_transformations[test_cases[t][0]]; 201 | var element_string = SVG_elements[test_cases[t][1]] 202 | 203 | var transformation = parseTransformString(transformation_str); 204 | var element = parseSVGString(element_string)[0]; 205 | 206 | var expected_result = test_cases[t][2]; 207 | var transformation_results = false; 208 | 209 | if (transformation) { transformation_results = transformation(element); } 210 | 211 | if (expected_result === 'null' || transformation_results != false && element.compareAttributes(expected_result)) { 212 | passed_count++; 213 | } else { 214 | console.log(" - " + test_cases[t][0] + " " + test_cases[t][1] + " failed"); 215 | console.log(element) 216 | } 217 | } 218 | console.log(" * Passed " + passed_count + " of " + test_cases.length); 219 | } 220 | 221 | var runTests = function() { 222 | testElementParsing(); 223 | testTransformationParsing(); 224 | testTransformations(); 225 | 226 | } -------------------------------------------------------------------------------- /Javascript/svg-optimiser.js: -------------------------------------------------------------------------------- 1 | function SVGElement() { 2 | 3 | this.extractAttributes = function(data) { 4 | // Extract a list of attributes from the passed data 5 | var attr = {}; 6 | data.each(function() { 7 | $.each(this.attributes, function(i, attrib) { 8 | attr[attrib.name] = attrib.value; 9 | }); 10 | }); 11 | 12 | this.attr = attr; 13 | 14 | for (var a in this.required_attributes) { 15 | var attribute = this.required_attributes[a]; 16 | if (attribute === "points" || attribute === "d") { 17 | if (!this.attr[attribute]) { this.attr[attribute] = ""; } 18 | this.parseCoordinates(this.attr[attribute]); 19 | } else { 20 | if (!this.attr[attribute]) { this.attr[attribute] = 0; } 21 | this.attr[attribute] = parseFloat(this.attr[attribute]); 22 | } 23 | } 24 | }; 25 | 26 | this.parseCoordinates = function(coords) { 27 | var coord_list = coords.split(/(?:\s*,\s*)|(?:\s+)/); 28 | this.coords = []; 29 | for (var i=0; i= 0 ? this.attr["r"] * sx : this.attr["r"] * -sx; 100 | } else { 101 | return false; 102 | } 103 | } 104 | } 105 | 106 | function SVG_Ellipse() { 107 | this.name = "ellipse"; 108 | this.required_attributes = ["cx", "cy", "rx", "ry"]; 109 | 110 | this.translate = function(dx, dy) { 111 | this.attr["cx"] += dx; 112 | this.attr["cy"] += dy; 113 | } 114 | 115 | this.scale = function(sx, sy) { 116 | this.attr["cx"] *= sx; 117 | this.attr["cy"] *= sy; 118 | 119 | if (sx >= 0) { 120 | this.attr["rx"] *= sx; 121 | } else { 122 | this.attr["rx"] *= -sx; 123 | } 124 | if (sy >= 0) { 125 | this.attr["ry"] *= sy; 126 | } else { 127 | this.attr["ry"] *= -sy; 128 | } 129 | } 130 | } 131 | 132 | function SVG_Rect() { 133 | this.name = "rect"; 134 | this.required_attributes = ["x", "y", "width", "height"]; 135 | 136 | this.translate = function(dx, dy) { 137 | this.attr["x"] += dx; 138 | this.attr["y"] += dy; 139 | } 140 | 141 | this.scale = function(sx, sy) { 142 | this.attr["x"] *= sx; 143 | this.attr["y"] *= sy; 144 | 145 | if (sx >= 0) { 146 | this.attr["width"] *= sx; 147 | } else { 148 | this.attr["width"] *= -sx; 149 | this.attr["x"] -= this.attr["width"] 150 | } 151 | if (sy >= 0) { 152 | this.attr["height"] *= sy; 153 | } else { 154 | this.attr["height"] *= -sy; 155 | this.attr["y"] -= this.attr["height"] 156 | } 157 | } 158 | } 159 | 160 | function SVG_Line() { 161 | this.name = "line"; 162 | this.required_attributes = ["x1", "y1", "x2", "y2"]; 163 | 164 | this.translate = function(dx, dy) { 165 | this.attr["x1"] += dx; 166 | this.attr["x2"] += dx; 167 | this.attr["y1"] += dy; 168 | this.attr["y2"] += dy; 169 | } 170 | 171 | this.scale = function(sx, sy) { 172 | this.attr["x1"] *= sx; 173 | this.attr["x2"] *= sx; 174 | this.attr["y1"] *= sy; 175 | this.attr["y2"] *= sy; 176 | } 177 | 178 | this.matrix = function(a, b, c, d, e, f) { 179 | var x = a * this.attr["x1"] + c * this.attr["y1"] + e; 180 | var y = b * this.attr["x1"] + d * this.attr["y1"] + f; 181 | this.attr["x1"] = x; 182 | this.attr["y1"] = y; 183 | 184 | var x = a * this.attr["x2"] + c * this.attr["y2"] + e; 185 | var y = b * this.attr["x2"] + d * this.attr["y2"] + f; 186 | this.attr["x2"] = x; 187 | this.attr["y2"] = y; 188 | } 189 | } 190 | 191 | function SVG_Polyline() { 192 | this.name = "polyline"; 193 | this.required_attributes = ["points"]; 194 | 195 | this.translate = function(dx, dy) { 196 | for (var i in this.coords){ 197 | this.coords[i][0] += dx; 198 | this.coords[i][1] += dy; 199 | } 200 | this.attr["points"] = this.coords.join(" "); 201 | } 202 | 203 | this.scale = function(sx, sy) { 204 | for (var i in this.coords){ 205 | this.coords[i][0] *= sx; 206 | this.coords[i][1] *= sy; 207 | } 208 | this.attr["points"] = this.coords.join(" "); 209 | } 210 | 211 | this.matrix = function(a, b, c, d, e, f) { 212 | for (var i in this.coords) { 213 | var x = a * this.coords[i][0] + c * this.coords[i][1] + e; 214 | var y = b * this.coords[i][0] + d * this.coords[i][1] + f; 215 | this.coords[i][0] = x; 216 | this.coords[i][1] = y; 217 | } 218 | this.attr["points"] = this.coords.join(" "); 219 | } 220 | } 221 | 222 | function SVG_Polygon() { 223 | this.name = "polygon"; 224 | } 225 | 226 | function SVG_Path() { 227 | this.name = "path"; 228 | this.required_attributes = ["d"]; 229 | this.commands = []; 230 | this.implemented_scales = ['M', 'm', 'L', 'l', 'q', 'Q', 't', 'T', 'c', 'C', 's', 'S']; 231 | this.simple_translations = ['M', 'L', 'Q', 'T', 'C', 'S']; 232 | this.null_translations = ['m', 'l', 'h', 'v', 'q', 't', 'c', 's']; 233 | 234 | this.parseCoordinates = function(coord_string) { 235 | // Should simplify to remove multiple M, m, H, h, V or v coordinates 236 | // [Optional] Remove repeated commands e.g. "L x1 y1 L x2 y2" -> "L x1 y1 x2 y2" 237 | 238 | var re_commands = /([ACHLMQSTV])([-\+\d\.\s,e]*)(z)?/gi 239 | 240 | while(commands = re_commands.exec(coord_string)){ 241 | var digits = extractDigits(commands[2]); 242 | var z = commands[3] ? "z" : ""; 243 | digits.unshift(commands[1]); 244 | digits.push(z); 245 | this.commands.push(digits) 246 | } 247 | 248 | if (this.commands[0][0] === 'm') { this.commands[0][0] = 'M' }; 249 | 250 | this.generatePathString(); 251 | } 252 | 253 | this.translate = function(dx, dy) { 254 | for (var i in this.commands) { 255 | var command = this.commands[i]; 256 | if ($.inArray(command[0], this.simple_translations) != -1) { 257 | for (var j=1; j 0) { 359 | return function(element) { 360 | return element.translate(digits[0], digits[1] ? digits[1] : 0); 361 | } 362 | } 363 | } 364 | 365 | if (scale_digits = re_scale.exec(transform_string)) { 366 | var digits = extractDigits(scale_digits[1]); 367 | if (digits.length > 0) { 368 | return function(element) { 369 | return element.scale(digits[0], digits[1] ? digits[1] : digits[0]); 370 | } 371 | } 372 | } 373 | 374 | if (matrix_digits = re_matrix.exec(transform_string)) { 375 | var digits = extractDigits(matrix_digits[1]); 376 | if (digits.length === 6) { 377 | return function(element) { 378 | return element.matrix(digits[0], digits[1], digits[2], digits[3], digits[4], digits[5]); 379 | } 380 | } 381 | } 382 | 383 | }; 384 | 385 | var applyTransform = function() { 386 | $('#error-message').html(""); 387 | 388 | var element = parseSVGString($("#input-svg").val()); 389 | if (!element) { 390 | $('#error-message').html("Unable to find any valid SVG elements"); 391 | return; 392 | } 393 | 394 | var transformation = parseTransformString($("#input-transformation").val()); 395 | if (!transformation) { 396 | $('#error-message').html("Unable to parse transformation"); 397 | return; 398 | } 399 | 400 | var transformed = transformation(element); 401 | if (transformed === false) { 402 | $('#error-message').html("That transformation is not implemented for this element"); 403 | return; 404 | } 405 | 406 | $("#output-svg").text(element.write()); 407 | }; 408 | 409 | var addExampleElement = function(element_name){ 410 | var element = SVG_elements[element_name]; 411 | $("#input-svg").val(element); 412 | } 413 | 414 | var addExampleTransformation = function(element_name){ 415 | var transformation = test_transformations[element_name]; 416 | $("#input-transformation").val(transformation); 417 | } 418 | 419 | $(document).ready(function() { 420 | $("#apply-button").on("click", function(event){ 421 | applyTransform(); 422 | }); 423 | $("#run-tests-button").on("click", function(event){ 424 | runTests(); 425 | }); 426 | }); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | License 2 | 3 | THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. 4 | 5 | BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 6 | 7 | 1. Definitions 8 | 9 | "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. 10 | "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. 11 | "Creative Commons Compatible License" means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. 12 | "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. 13 | "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 14 | "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. 15 | "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. 16 | "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. 17 | "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 18 | "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. 19 | "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 20 | 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 21 | 22 | 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: 23 | 24 | to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; 25 | to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; 26 | to Distribute and Publicly Perform the Work including as incorporated in Collections; and, 27 | to Distribute and Publicly Perform Adaptations. 28 | For the avoidance of doubt: 29 | 30 | Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; 31 | Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, 32 | Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. 33 | The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 34 | 35 | 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 36 | 37 | You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. 38 | You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. 39 | If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. 40 | Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 41 | 5. Representations, Warranties and Disclaimer 42 | 43 | UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 44 | 45 | 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 46 | 47 | 7. Termination 48 | 49 | This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. 50 | Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 51 | 8. Miscellaneous 52 | 53 | Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. 54 | Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. 55 | If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 56 | No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. 57 | This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. 58 | The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. 59 | -------------------------------------------------------------------------------- /cleanSVG.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from lxml import etree 4 | import re 5 | import os 6 | import sys 7 | 8 | # Regex 9 | re_transform = re.compile('([a-zA-Z]+)\((-?\d+\.?\d*),?\s*(-?\d+\.?\d*)?\)') 10 | re_translate = re.compile('\((-?\d+\.?\d*)\s*,?\s*(-?\d+\.?\d*)\)') 11 | re_coord_split = re.compile('\s+|,') 12 | re_path_coords = re.compile('[a-zA-Z]') 13 | re_path_split = re.compile('([ACHLMQSTVZachlmqstvz])') 14 | re_trailing_zeros = re.compile('\.(\d*?)(0+)$') 15 | re_length = re.compile('^(\d+\.?\d*)\s*(em|ex|px|in|cm|mm|pt|pc|%|\w*)') 16 | 17 | # Path commands 18 | path_commands = { 19 | "M": (0, 1), 20 | "L": (0, 1), 21 | "T": (0, 1), 22 | "H": (0), 23 | "V": (1), 24 | "A": (-1, -1, -1, -1, -1, 0, 1), 25 | "C": (0, 1, 0, 1, 0, 1) 26 | } 27 | 28 | # How relative commands are scaled 29 | scale_commands = { 30 | "m": (0, 1), 31 | "l": (0, 1), 32 | "t": (0, 1), 33 | "h": (0), 34 | "v": (1), 35 | "a": (0, 1, -1, -1, -1, 0, 1), 36 | "c": (0, 1, 0, 1, 0, 1) 37 | } 38 | scale_commands.update(path_commands) 39 | 40 | # Attribute names 41 | value_attributes = ["x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry", "width", "height"] 42 | default_styles = set([ 43 | ("opacity", "1"), 44 | ("fill-opacity", "1"), 45 | ("stroke", "none"), 46 | ("stroke-width", "1"), 47 | ("stroke-opacity", "1"), 48 | ("stroke-miterlimit", "4"), 49 | ("stroke-linecap", "butt"), 50 | ("stroke-linejoin", "miter"), 51 | ("stroke-dasharray", "none"), 52 | ("stroke-dashoffset", "0"), 53 | ("font-anchor", "start"), 54 | ("font-style", "normal"), 55 | ("font-weight", "normal"), 56 | ("font-stretch", "normal"), 57 | ("font-variant", "normal") 58 | ]) 59 | 60 | position_attributes = {"rect": (["x", "y"]), 61 | "tspan": (["x", "y"]), 62 | "circle": (["cx", "cy"]), 63 | "ellipse": (["cx", "cy"]), 64 | "line": (["x1", "y1", "x2", "y2"])} 65 | 66 | scaling_attributes = {"rect": (["x", "y", "width", "height"]),} 67 | 68 | STYLES = set([ 69 | "alignment-baseline", 70 | "baseline-shift", 71 | "clip-path", 72 | "clip-rule", 73 | "color-interpolation", 74 | "color-interpolation-filters", 75 | "color-profile", 76 | "color-rendering", 77 | "direction", 78 | "dominant-baseline", 79 | "fill", 80 | "fill-opacity", 81 | "fill-rule", 82 | "font", 83 | "font-family", 84 | "font-size", 85 | "font-size-adjust", 86 | "font-stretch", 87 | "font-style", 88 | "font-variant", 89 | "font-weight", 90 | "glyph-orientation-horizontal", 91 | "glyph-orientation-vertical", 92 | "image-rendering", 93 | "kerning", 94 | "letter-spacing", 95 | "marker", 96 | "marker-end", 97 | "marker-mid", 98 | "marker-start", 99 | "mask", 100 | "opacity", 101 | "pointer-events", 102 | "shape-rendering", 103 | "stop-color", 104 | "stop-opacity", 105 | "stroke", 106 | "stroke-dasharray", 107 | "stroke-dashoffset", 108 | "stroke-linecap", 109 | "stroke-linejoin", 110 | "stroke-miterlimit", 111 | "stroke-opacity", 112 | "stroke-width", 113 | "text-anchor", 114 | "text-decoration", 115 | "text-rendering", 116 | "unicode-bidi", 117 | "word-spacing", 118 | "writing-mode", 119 | ]) 120 | 121 | class CleanSVG: 122 | def __init__(self, svgfile=None, verbose=False): 123 | self._verbose = verbose 124 | self.tree = None 125 | self.root = None 126 | 127 | # Need to update this if style elements found 128 | self.styles = {} 129 | self.style_counter = 0 130 | 131 | self.num_format = "%s" 132 | self.removeWhitespace = True 133 | 134 | if svgfile: 135 | self.parseFile(svgfile) 136 | 137 | def parseFile(self, filename): 138 | try: 139 | self.tree = etree.parse(filename) 140 | except IOError: 141 | print "Unable to open file", filename 142 | sys.exit(1) 143 | 144 | self.root = self.tree.getroot() 145 | 146 | def analyse(self): 147 | """ Search for namespaces. Will do more later """ 148 | 149 | print "Namespaces:" 150 | for ns, link in self.root.nsmap.iteritems(): 151 | print " %s: %s" % (ns, link) 152 | 153 | def removeGroups(self): 154 | """ Remove groups with no attributes """ 155 | # Doesn't work for nested groups 156 | 157 | for element in self.tree.iter(): 158 | if not isinstance(element.tag, basestring): 159 | continue 160 | 161 | element_type = element.tag.split('}')[1] 162 | if element_type == 'g' and not element.keys(): 163 | parent = element.getparent() 164 | if parent is not None: 165 | parent_postion = parent.index(element) 166 | print 167 | print parent 168 | # Move children outside of group 169 | for i, child in enumerate(element, parent_postion): 170 | print i 171 | print "move %s to %s" % (child, i) 172 | parent.insert(i, child) 173 | 174 | #del parent[i] 175 | 176 | def write(self, filename): 177 | """ Write current SVG to a file. """ 178 | 179 | if not filename.endswith('.svg'): 180 | filename += '.svg' 181 | 182 | with open(filename, 'w') as f: 183 | f.write(self.toString(True)) 184 | 185 | def toString(self, pretty_print=False): 186 | """ Return a string of the current SVG """ 187 | 188 | if self.styles: 189 | self._addStyleElement() 190 | 191 | if self.removeWhitespace: 192 | svg_string = etree.tostring(self.root) 193 | svg_string = re.sub(r'\n\s*' , "", svg_string) 194 | else: 195 | svg_string = etree.tostring(self.root, pretty_print=pretty_print) 196 | 197 | return svg_string 198 | 199 | def _addStyleElement(self): 200 | """ Insert a CSS style element containing information 201 | from self.styles to the top of the file. """ 202 | 203 | style_element = etree.SubElement(self.root, "style") 204 | self.root.insert(0, style_element) 205 | style_text = '\n' 206 | 207 | for styles, style_class in sorted(self.styles.iteritems(), key=lambda (k,v): v): 208 | style_text += "\t.%s{\n" % style_class 209 | for (style_id, style_value) in styles: 210 | style_text += '\t\t%s:\t%s;\n' % (style_id, style_value) 211 | style_text += "\t}\n" 212 | 213 | style_element.text = style_text 214 | 215 | def setDecimalPlaces(self, decimal_places): 216 | """ Round attribute numbers to a given number of decimal places. """ 217 | 218 | self.num_format = "%%.%df" % decimal_places 219 | 220 | for element in self.tree.iter(): 221 | if not isinstance(element.tag, basestring): 222 | continue 223 | 224 | tag = element.tag.split('}')[1] 225 | 226 | if tag == "polyline" or tag == "polygon": 227 | values = re_coord_split.split(element.get("points")) 228 | formatted_values = [self._formatNumber(x) for x in values if x] 229 | try: 230 | point_list = " ".join((formatted_values[i] + "," + formatted_values[i+1] for i in range(0, len(formatted_values), 2))) 231 | element.set("points", point_list) 232 | except IndexError: 233 | print "Could not parse points list" 234 | pass 235 | 236 | elif tag == "path": 237 | coords = map(self._formatNumber, re_coord_split.split(element.get("d"))) 238 | coord_list = " ".join(coords) 239 | element.set("d", coord_list) 240 | #for coord in coords: 241 | # if re_path_coords.match(coord): 242 | # print coord 243 | 244 | else: 245 | for attribute in element.attrib.keys(): 246 | if attribute in value_attributes: 247 | element.set(attribute, self._formatNumber(element.get(attribute))) 248 | 249 | def removeAttribute(self, attribute, exception_list=None): 250 | """ Remove all instances of an attribute ignoring any with a value in the exception list. """ 251 | 252 | if exception_list is None: exception_list = [] 253 | 254 | if self._verbose: print '\nRemoving attribute: %s' % attribute 255 | 256 | for element in self.tree.iter(): 257 | if attribute in element.attrib.keys() and element.attrib[attribute] not in exception_list: 258 | if self._verbose: print ' - Removed attribute: %s="%s"' % (attribute, element.attrib[attribute]) 259 | del element.attrib[attribute] 260 | 261 | def removeElement(self, tagName): 262 | """ Remove all instances of an element. """ 263 | 264 | if self._verbose: print '\nRemoving element: %s' % tagName 265 | 266 | for element in self.tree.iter(): 267 | if (isinstance(element.tag, basestring)): 268 | tag = element.tag.split('}')[1] 269 | if tag == tagName: 270 | element.getparent().remove(element) 271 | 272 | def removeComments(self): 273 | """ Remove all comments. """ 274 | 275 | if self._verbose: print '\nRemoving comments' 276 | 277 | for element in self.tree.iter(): 278 | if element.tag is etree.Comment: 279 | element.getparent().remove(element) 280 | 281 | def removeNonDefIDAttributes(self): 282 | """ Go through def elements and find IDs referred to, then remove all IDs except those. """ 283 | 284 | def_IDs = [] 285 | 286 | for element in self.tree.iter(): 287 | if not isinstance(element.tag, basestring): 288 | continue 289 | 290 | tag = element.tag.split('}')[1] 291 | if tag == 'defs': 292 | for child in element.getchildren(): 293 | for key, value in child.attrib.iteritems(): 294 | if key.endswith('href'): 295 | def_IDs.append(value) 296 | 297 | self.removeAttribute('id', exception_list=def_IDs) 298 | 299 | def removeNamespace(self, namespace): 300 | """ Remove all attributes of a given namespace. """ 301 | 302 | nslink = self.root.nsmap.get(namespace) 303 | 304 | if self._verbose: 305 | print "\nRemoving namespace, %s" % namespace 306 | if nslink: 307 | print " - Link: %s" % nslink 308 | 309 | if nslink: 310 | nslink = "{%s}" % nslink 311 | length = len(nslink) 312 | 313 | for element in self.tree.iter(): 314 | if element.tag[:length] == nslink: 315 | self.root.remove(element) 316 | if self._verbose: 317 | print " - removed element: %s" % element.tag[length:] 318 | 319 | for attribute in element.attrib.keys(): 320 | if attribute[:length] == nslink: 321 | del element.attrib[attribute] 322 | if self._verbose: 323 | print " - removed attribute from tag: %s" % element.tag 324 | 325 | del self.root.nsmap[namespace] 326 | 327 | def extractStyles(self): 328 | """ Remove style attributes and values of the style attribute and put in