0

My users can upload image files, which could be SVGs.

I need to make sure that all SVGs have a width and height attribute for something that's occurring later on.

If I have the SVG as a file (via an input type="file") how can I add a width and height to it if it is missing?

user2445278
  • 808
  • 1
  • 8
  • 15
  • Does this answer your question? [How do you get the width and height of an SVG picture in PHP?](https://stackoverflow.com/questions/6532261/how-do-you-get-the-width-and-height-of-an-svg-picture-in-php) – SKJ Jan 19 '22 at 19:04

1 Answers1

0

I ended up doing the following, though Im sure it could be improved/done in a much better way

 let svgReader = new FileReader();
               
        svgReader.onload = function (e) {
            let svg = $(e.target.result);

            for(let i =0;i<svg.length;i++) {
                if (svg[i] instanceof SVGElement) {
                    svg = $(svg[i]);
                    break;
                }
            }

            let width = svg.attr("width");
            let height = svg.attr("height");
            if (height == null || height == undefined) {
                svg.attr("height", 300);
            }

            if (width == null || width == undefined) {
                svg.attr("height", 300);
            }

            let svgFile = new XMLSerializer().serializeToString(svg[0]);
            let new file = new File([svgFile], files[index].name, {type: "image/svg+xml"});
        };
svgReader.readAsText(files[0]);

I had to go through the SVG to find an instance of SVG element, as some of the SVGs I tested with had additional tags or comments that messed it up otherwise. Also, the 300 value for width and height was just made up, but seems to be ok, probably could have used the view box dimensions instead, but it works for me

user2445278
  • 808
  • 1
  • 8
  • 15