DEV Community

James Moberg
James Moberg

Posted on

Parsing Width/Height from SVG File using ColdFusion

Someone on the Lucee website asked how to get width/height of SVG image file in Lucee. I tend use a lot of SVG images when generating PDFs using WKHTMLTOPDF with ColdFusion 2016-2021 and Lucee. I thought I'd try writing a cross-compatible UDF to parse this information. I've added support for desc, title and id metadata. The dimensions will be pulled from svg.viewBox (if exists) rather than width and height tags as I noticed that these dimensions seemed to be used more often with some generators. (NOTE: While the "S" in SVG means that images "scaleable", the dimensions are still extremely beneficial when embedding so you can explicitly code the dimensions using the correct aspect ratio.)

Some SVG images used decimal width/height values while others used integers. Some also contained a "px" unit. I chose to output a numeric double or integer value without the unit. I also read that the default dimensions used by Chrome was 300x150, so it defaults to these dimensions if nothing can be parsed.

Here's the UDF. Enjoy!

https://gist.github.com/JamoCA/baa454a6a5381e7339548a1f627ce1c3

Top comments (0)