37

first of all I know that there are many similar questions like this, but none of them seem to do the trick for me. I'd like to know if there is any way to combine multiple svg files within one single file. Somewhat like this:

<svg id="background" ...>
   <svg id="first" ...>
       ...
   </svg>
   <svg id="second" ...>
       ...
   </svg>
   ...
</svg>

Is there some sort of template or tutorial that helps me do this? In the end I want to do this programmatically using java und javafx 2.2.

1

9 Answers 9

8

To change the SVG in exactly that way, you should check out my SVG Stacking Tool. As SVGs are XML one can use XSLT to transform the data:

Update: As pointed out in the comments, there seems to be a bug so that the SVG file is requested multiple times. More details and a possible solution can be found here:

3
  • 1
    Looking at your SVG Stacking Demo, the chrome devtools network waterfall diagram seems to suggest that social.svg is loaded from the server multiple times?
    – Codemonkey
    Nov 9, 2014 at 19:04
  • 4
    "This repository has been archived by the owner. It is now read-only." Dec 21, 2018 at 19:50
  • Mentioned solution has problem with the viewBox - not able to resize properly selected layer to display Jun 8, 2020 at 19:20
6

You may try svg-join for combine multiple SVG in one symbol collection.

This tool create two files for you. The first is "svg-bundle.svg":

<svg ...>
  <symbol id="svg1" ...>
  <symbol id="svg2" ...>
</svg>

Every symbol is your separate SVG file.

The last one is "svg-bundle.css":

.svg_svg1,
.svg_svg2 {
  width: 20px; // for example
  height: 20px;
}

Now you may use it in your html:

<link rel="stylesheet" type="text/css" href="svg-bundle.css" />
...
<svg class="svg_svg1"><use xlink:href="svg-bundle.svg#svg1"></svg>
<svg class="svg_svg2"><use xlink:href="svg-bundle.svg#svg2"></svg>
1
  • 5
    svg-join is generating files with content not recognized by Firefox, Inkscape and GNOME image preview. Dec 21, 2018 at 19:43
2

After searching a lot of resource, I fount there is a python solution which is really handy: https://github.com/astraw/svg_stack

Say you have two svg file in hand, 11.svg 12.svg, what you can do is:

python svg_stack.py --direction=h --margin=100 11.svg 12.svg > 1.svg

You may think to have 6 svg files to lay out in this way:

11 12
21 22
31 32

which you can do following step:

# merge 11 12
python svg_stack.py --direction=h --margin=100 11.svg 12.svg > 1.svg
# merge 21 22
python svg_stack.py --direction=h --margin=100 21.svg 22.svg > 2.svg
# merge 31 32
python svg_stack.py --direction=h --margin=100 31.svg 32.svg > 3.svg
# merge all
python svg_stack.py --direction=v --margin=100 1.svg 2.svg 3.svg > final.svg

note that you can change merge direction using v and h

2

For those, who use npm and task runners like grunt or gulp I'd highly recommend using the following node module: https://github.com/svg-sprite/svg-sprite

It takes a bunch of SVG files, optimizes them and bakes them into SVG sprites of several types along with suitable stylesheet resources.

It's configurable, so its possible to create both sprite modes <view> and <symbol>. So they could be used in both html and css.

Mode configuration looks as follows:

// Common mode properties
const config = {
    mode: {
        <mode>: {
            dest: "<mode>", // Mode specific output directory
            prefix: "svg-%s", // Prefix for CSS selectors
            dimensions: "-dims", // Suffix for dimension CSS selectors
            sprite: "svg/sprite.<mode>.svg", // Sprite path and name
            bust: true || false, // Cache busting (mode dependent default value)
            render: { // Stylesheet rendering definitions
                /* -------------------------------------------
                css: false, // CSS stylesheet options
                scss: false, // Sass stylesheet options
                less: false, // LESS stylesheet options
                styl: false, // Stylus stylesheet options
                <custom>: ... // Custom stylesheet options
                -------------------------------------------    */
            },
            example: false // Create an HTML example document
        }
    }
}

For more details, refer to their Docs.

1

I think the best and easiest way is to do this, assuming you only need to support the latest two major versions of major browsers, Android 9 Chrome, iOS 13 Safari, Desktop: Chrome, Firefox, Safari, Edge 87.

1 EDIT: First compress all the SVGs as they might break inside CSS otherwise using for example https://jakearchibald.github.io/svgomg/

2 Create a separate stylesheet and embed the svgs:

.icon-1 {
  background-image: url('data:image/svg+xml;utf8,<svg>...</svg>');
}
.icon-2 {
  background-image: url('data:image/svg+xml;utf8,<svg>...</svg>');
}

3 Lazy load this stylesheet with js - since these sorts of stylesheets tends to become very big and usually aren't needed to block rendering of the page.

I escaped # with %23(do not know if it's really necessary) it seems like you do not need to escape regular svgs in other ways - haven't tested if they contain inline style tags though (these styles can be moved to your stylesheet anyway)

1

I used Victor gem https://github.com/DannyBen/victor

first_svg = File.open("first.svg").read
second_svg = File.open("second.svg").read

first_content = first_svg.split("\n")[1..-2].join(", ")
second_content = second_svg.split("\n")[1..-2].join(", ")

svg = Victor::SVG.new width: "100%", height: "100%"
svg << first_content
svg << second_content

svg.save 'final.svg'
0

maybe you can use svg-sprite, it's a nodejs tool

svg-sprite is a low-level Node.js module that takes a bunch of SVG files, optimizes them and bakes them into SVG sprites

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Apr 19, 2022 at 12:03
0

I found out that is was not very easy to create a SVG file from different PNG or SVG files. Using all kind of different tools gave the best result.

First of all, the following website gives a clear explanation of what we want to achieve: https://css-tricks.com/svg-fragment-identifiers-work/

These are the tools I used:

  1. Wikipedia: I needed country flags and these can be downloaded in SVG format from Wikipedia.

  2. Adobe Express (https://express.adobe.com/nl-NL/tools/convert-to-svg ): To convert a PNG image (a raster graphic) to a good quality SVG file (a vector graphic) online.

  3. iloveimg - resize-svg (https://www.iloveimg.com/resize-image/resize-svg): To resize my SVG images online so they all have the same size (meaning the same dimensions).

  4. SVG Optimizer (https://github.com/svg/svgo): For optimizing the SVG files. SVG Optimizer is a Node.js-based tool which you have to install on your computer.

  5. SVG Join (https://github.com/Climenty/svg-join): For joining (merging) the SVG file into one SVG file. SVG Join is a Node.js-based tool which you have to install on your computer.

  6. A text editor: To modify the new SVG file. I added the following code just below the first SVG tag:

    <view id="it" viewBox="0    0 750 500" />
    <view id="nl" viewBox="0  500 750 500" />
    <view id="en" viewBox="0 1000 750 500" />
    <view id="de" viewBox="0 1500 750 500" />
    <view id="fr" viewBox="0 2000 750 500" />
    <view id="es" viewBox="0 2500 750 500" />
    

You can see the code of the merged SVG file here:

https://gist.github.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18?short_path=c14e150

.flag {
  width: 75px;
  height: 50px;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Flags</title>
</head>
<body>
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#en" alt="English">
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#es" alt="Spanish">
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#nl" alt="Dutch">
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#it" alt="Italian">
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#fr" alt="French">
    <img class="flag" src="https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg#de" alt="German">
</body>
</html>

Some notes:

The merged SVG file in the example is hosted on GitHub. Here are the links:

SVG code (Display the source blob): https://gist.github.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18?short_path=c14e150

SVG image (Display the image): https://gist.githubusercontent.com/R-W-C/0ccbcc1e5ca014a83a305d550c197a18/raw/9989a7ff58f28d55072aab20a83228f2e84e62e1/flags.svg

-9

Are you saying you have entirely distinct SVG documents? In that case, what is the point of trying to cram them into one document? I'm confused.

If what you mean is you want to enclose one svg element in another, that's entirely possible, and in that sense your sample is syntactically correct.

If for some reason you really want to hold what are intrinsically distinct documents in a single SVG document, then I suppose you could use CSS to turn the display of each on and off.

#first, #second { display: none; }
.display-first #first { display: block; }
.display-second #second { display: block; }

function toggle_first () { document.body.classList.toggle("first"); }

or something along those lines.

3
  • 4
    The purpose placing multiple SVG documents into one is to reduce the number of requests done by the server (like sprites). This should be done with fragment identifiers broken-links.com/2012/08/14/… but they are only supported by Firefox. The accepted workaround solution is what you posted (you arrived to the same solution independently!). Jan 28, 2013 at 16:49
  • It can also be useful for stacking images onto a single sheet for printing. Mar 26, 2021 at 1:47
  • SVG fonts use this, too. Nov 17, 2021 at 1:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.