SVG
SVG copied to clipboard
Setting `SvgDocument.ViewBox` does not change the output of `SvgDocument.Draw()`
Description
Setting SvgDocument.ViewBox
does not change the output of SvgDocument.Draw()
I am trying to programmatically convert an SVG file into a PNG file. The SVG has some whitespace around the edges that I would like to get rid of. I want to trim the whitespace before converting to PNG, because the SVG size without whitespace will determine how large I need to scale the SVG.
The general approach I have seen on a lot of sites for trimming SVG's in HTML/JS is to set the viewBox to be the same as the boundingBox.
Here is a StackOverflow question I opened about this issue.
Example data
Here is my attempt to do this with SVG.NET and F#
let svg = SvgDocument.Open("original.svg")
let bmp1 = svg.Draw()
bmp1.Save("original.png", ImageFormat.Png)
let bounds = svg.Bounds
svg.ViewBox <- SvgViewBox(bounds.Left, bounds.Top, bounds.Width, bounds.Height)
let bmp2 = svg.Draw()
bmp2.Save("trimmed.png", ImageFormat.Png)
If I set a breakpoint, I can see that bounds
looks like it has the right dimensions. However, the generated original.png
and trimmed.png
are identical.
Used Versions
- SVG.NET 3.4.2
- .NET 6.0
- Windows 10
@jfaixolo
Will adding the following settings give you the results you expect ?
svg.AspectRatio = new SvgAspectRatio(SvgPreserveAspectRatio.xMinYMin);
If you also want to resize png image, use Draw
method that gives a bitmap.