How to split an SVG file with dozens of g elements into dozens of SVG files?

I have an SVG file that has, say, 10 g elements that do not start at (0,0). For example:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">
<svg version="1.1" xmlns="" xmlns:xlink="" x="0px" y="0px" width="528px"
     height="240px" viewBox="0 0 528 240" enable-background="new 0 0 528 240" xml:space="preserve">
<g id="CONTAINER">
    <g id="collapse-top">
        <path id="collapse_x5F_top" fill="#1D1D1B" d="M498,206v-3c0-2.2-1.8-4-4-4h-3c-2.2,0-4,1.8-4,4v3c0,2.156,1.781,4,4,4
            c0,0,2,0,3,0C496.172,210,498,208.156,498,206z M496,207c0,0.55-0.45,1-1,1h-5c-0.55,0-1-0.45-1-1v-5c0-0.55,0.45-1,1-1h5
            c0.55,0,1,0.45,1,1V207z M495,206h-5l2.5-3.333L495,206z"/>

How can I split it into 10 different SVG files, one per g element, that each start at (0,0)?

I prefer an automated, command-line based approach to do this, but I can use Adobe Illustrator as well.


There are a couple ways I can think of to do this:

Option 1: Modify the d attribute on the Object

Difficulty rating: ★★★★☆

Conceptually, this is pretty simple. The nitty gritty details are the issue. in the <path> object within the <g>, you have the d attribute. This is the main thing you need to modify. What you’ll need to do is decode that and translate it to the updated coordinates.

Option 2: Add a transform Attribute to the Object

Difficulty rating: ★★☆☆☆

If you have a good grasp with JavaScript, this is pretty easy. You can get the bounding box of the graphic using getBBox(). You can then use that rect to add a transform attribute to the object, like so:

transform = "translate(-100 -100)"

This would move the object 100 units to the left and 100 units up. Using the example you provided, I added the following script:

<script type="application/ecmascript"> <![CDATA[
  var path = document.getElementById("collapse_x5F_top");
  var x = path.getBBox().x;
  var y = path.getBBox().y;

  path.setAttribute("transform", "translate(-" + x + " -" + y + ")");
]]> </script>

This moves the graphic to the top right corner of the screen.

Live Demo (The red icon is the original, the black is the transformed object)

**Please note that while this code works for this example, it is not robust code that will work for every test case (for instance, if values of x and y are not initially positive)

Source : Link , Question Author : TheFooProgrammer , Answer Author : JohnB

Leave a Comment