examinedliving
9/15/2016 - 1:22 PM

Imports folder full of svg files into symbols named after the file name into active illustrator document. Requires underscore.js (although

Imports folder full of svg files into symbols named after the file name into active illustrator document. Requires underscore.js (although could easily be modified not to), so sett pathToUnderscore variable to underscore.js file. Also, extendscript has problems with the minified version of underscore for some reason, so use non-minified version.

var pathToUnderscore = "D:/Scripts/AI/underscore.js";
# include pathToUnderscore;

// utility function 
function getSymbolsPerRow(size, doc) {
	var docWidth = doc.width;
	var count = (docWidth / (size + 20));
	return count;
}

// creates new symbol
function createSymbol(name, doc) {
	var layer = doc.layers.getByName(name);
	var obj = layer.groupItems[0];
	var symbol = doc.symbols.add(obj);
	symbol.name = name;
}

// imports svg files as grid and resizes them
function importSVG(folder, size, create) {
	size = size || 32;
	var doc = app.activeDocument;
	var location = Folder(folder);
	var files = location.getFiles('*.svg');
	var lastX = 10,
		lastY = -10;
	var totalCount = getSymbolsPerRow(size, doc);
	var count = 0;
	var layer, name, obj, oldWidth, oldHeight, pct, h, left, top;
	_.each(files, function(e, i) {

		layer = doc.layers.add();
		name = e.displayName.replace('.svg', '');
		layer.name = name;

		obj = doc.groupItems.createFromFile(e);
		oldWidth = obj.width;
		oldHeight = obj.height;
		pct = size / oldWidth;
		h = oldHeight * pct;

		if (count >= totalCount) {
			top = lastY - h - 20;
			lastY = top;
			left = 10;
			lastX = left;
			count = 0;
		} else {
			top = lastY;
			left = lastX + 10 + size;
			lastX = left;
		}

		obj.width = size;
		obj.height = h;
		obj.top = top;
		obj.left = left;
		obj.parent = layer;
		$.writeln(name);
		if (create) {

			createSymbol(name, doc);
		}

		count++;

	});
}

var folder = {{folder}};
// importSVG(folder, 32, true);