Skip to content

Instantly share code, notes, and snippets.

@gka
Created December 23, 2015 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gka/c97465e7a25d943e1191 to your computer and use it in GitHub Desktop.
Save gka/c97465e7a25d943e1191 to your computer and use it in GitHub Desktop.
Script to remove markup for hidden elements from SVG files, for use with ai2html
var fs = require('fs'),
cheerio = require('cheerio'),
fn = process.argv[2];
cleanSVGArtboard(fn);
function cleanSVGArtboard(svgFileName, svg_embed_images) {
if (!fs.existsSync(svgFileName)) return;
var svgText = fs.readFileSync(svgFileName, 'utf-8');
if (svgText.indexOf('non-scaling-stroke') > -1) {
// already cleaned
return;
}
svgText = svgText.replace('xml:space="preserve">',
'xml:space="preserve">\n\t<style>\n\t\tpath,line,circle,rect,polygon { vector-effect: non-scaling-stroke }\n\t</style>\n');
svgText = svgText.replace(/style="display:none/g, 'data-hide="1" style="display:none');
var $ = cheerio.load(svgText, {normalizeWhitespace: true, xmlMode: true});
$('*[data-hide=1]').remove();
$('text').remove();
if (!svg_embed_images) $('image').remove();
// remove three levels of empty divs
$('g:empty').remove();
$('g:empty').remove();
$('g:empty').remove();
fs.writeFileSync(svgFileName, $.xml(), 'utf8');
console.log('cleaned '+fn);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment