4
$\begingroup$

I Export a Graphics object to SVG, but how do I control the bounding box in the resulting SVG file? Here's my code:

g1 = Graphics[Circle[{0, 0}, 4]]; 
g2 = Graphics[Line[{{0, 0}, {1, 0}, {0, 1}, {0, 0}}]];
g3 = Graphics[Arrow[{{0, 0}, {-1, -1}/2}]];
g = Show[g1, g2, g3, ImageSize -> {200, 100}]
Export["Mathematica.svg", g]

The result is an SVG image with width="149pt" and height="99pt". How do I control these parameters in the code?

$\endgroup$
  • 1
    $\begingroup$ Are you trying to preserve the whitespace around the graphic? $\endgroup$ – Graumagier Apr 16 '17 at 14:12
  • $\begingroup$ I need the bounding box of the right shape and relative sizes of all elements to be correct. If you run my code with ImageSize -> {2000, 1000}, you will see that the contents don't even fit in the bounding box. $\endgroup$ – Wynne Apr 17 '17 at 14:37
2
$\begingroup$

(Outputs here are for Mathematica 11.1.0.)

You are exporting a circular object with equal width and height but specify larger width than the height via the ImageSize -> {200, 100} option. Hence some margins are added from the left and the right, but the height is kept as you specified (height="99pt" corresponds to the height 100 pts). With automatic width or height you get them equal:

StringCases[ExportString[Show[g1, g2, g3, ImageSize -> {Automatic, 100}], "SVG"], 
 "<svg" ~~ Shortest[__] ~~ ">"]
{"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \
width=\"99pt\" height=\"99pt\" viewBox=\"0 0 99 99\" version=\"1.1\">"}

You do control these parameters via the ImageSize option but for some reason the values are only approximately equal to what you specify:

StringCases[ExportString[Show[g1, g2, g3, ImageSize -> {Automatic, 1000}], "SVG"], 
 "<svg" ~~ Shortest[__] ~~ ">"]
{"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \
width=\"981pt\" height=\"981pt\" viewBox=\"0 0 981 981\" version=\"1.1\">"}

If you run my code with ImageSize -> {2000, 1000}, you will see that the contents don't even fit in the bounding box.

When I render the exported SVG file with Internet Explorer or Firefox I do not see any cropping:

screenshot

Opening the file with Adobe Illustrator 17 also shows no cropping:

screenshot2

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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