svg

how to shrink / normalize an SVG so it fits in a specific viewbox


I used dozens of SVGs in my current app, they are all inline and they are all normalized.. meaning that all of them have a viewbox of 0 0 24 24 and the icon fits nicely in the middle

Then this designer just gave me multiple new SVGs and they are not standard.. they have viewboxes of 0 0 1024 1024, 0 0 400 400, 0 0 72 72

I want to normalize them so they all have a viewbox of 0 0 24 24.

I tried opening them in vectr.com and I united the paths and then shrunk them and exported the SVG again and sure enough they are much smaller now, however they do not fit 0 0 24 24 exactly.. I need to trial and error it and for example the 0 0 1024 1024 is now 0 0 48 40

I'm sure there's an editor / tool that could have done a perfect job of shrinking it and centering it in such a way that it would fit 0 0 24 24

How can I go about achieving this easily and simply?

Thank you


Solution

  • I would have never thought of such a use case, but if you have exactly one path as the svg content, my own library pathfit can rewrite the the path in that way. Here is a node.js script:

    const Pathfit = require('pathfit');
    
    function shrinkPath (path, viewBox, targetWidth, targetHeight) {
        const pathfitter = new Pathfit({viewBox}, undefined, path);
    
        return pathfitter.scale_with_aspect_ratio(targetWidth, targetHeight);
    }