Skip to content

Instantly share code, notes, and snippets.

@abarreir
Created October 16, 2014 18:58
Show Gist options
  • Save abarreir/c769e449b65ce029aedd to your computer and use it in GitHub Desktop.
Save abarreir/c769e449b65ce029aedd to your computer and use it in GitHub Desktop.
Generate viewBox attributes for svgs based on width and height when set
var fs = require('fs');
var DOMParser = require('xmldom').DOMParser;
var XMLSerializer = require('xmldom').XMLSerializer;
var addViewboxToSvg = function(svgPath) {
fs.readFile(svgPath, 'utf-8', function(error, svgStr) {
if (error) {
return console.log(error)
}
var doc = new DOMParser().parseFromString(svgStr, 'text/xml');
if (!doc.documentElement.hasAttribute('viewBox')) {
var width = doc.documentElement.getAttribute('width');
var height = doc.documentElement.getAttribute('height');
if (width && height) {
doc.documentElement.setAttribute('viewBox', '0 0 ' + parseInt(width) + ' ' + parseInt(height));
var docStr = new XMLSerializer().serializeToString(doc);
fs.writeFile(svgPath, docStr, function(error) {
if (error) {
console.log(error);
}
});
}
}
});
};
var svgsFolder = 'dashlane_scan_exports_norm';
fs.readdir(svgsFolder, function(error, files) {
if (error) {
return console.log(error);
}
files
.filter(function(file) {
return file.substr(-4) === '.svg';
})
.forEach(function(filename) {
addViewboxToSvg(svgsFolder + '/' + filename);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment