javascriptarrayscsvadobe-illustrator

Illustrator javascript CSV to Array to pathItems coordinates


I have a CSV File with the following data:

10, 23, 55, 123, 150 ...

I have a Javascript File which I use in Adobe Illustrator.

The following code creates 10 rectangles that are each shifted by 20 pixels and placed on the artboard. So far it works.

var myDocument = app.activeDocument;
var artLayer = myDocument.activeLayer;
var mypos = 0;
var i = 0;
while (i < 10) {
    var rect = artLayer.pathItems.rectangle( 0, mypos, 200, 600 );
    i++;
    mypos = mypos + 20;
  }

Now I want to use the values ​​from the CSV file for the coordinates/position of the rectangles instead of mypos + 20. The open dialog appears and I can select the CSV file.So far it works.

Now I don't know how to process the data from the CSV file and go through the array to use the values.

  var csvFile = File.openDialog("Choose CSV file.", "*.csv");
    var csvContents = "";
    if (csvFile) {
       csvFile.open('r');
       csvContents = csvFile.read();
       csvFile.close();
    }

Solution

  • This is roughly what you'll want to do:

    1. Parse the CSV file into an array of values
    2. Cycle through each value in the array
    3. Render a square on screen at the coordinate corresponding to this value

    To create one row of rectangles (i.e. all with the same y coordinates), you want to use a forEach loop:

    // Split CSV line into array of x-coordinates
    let xCoordinates = csvContents.split(',');
    // Cycle through all the x-coordinates
    xCoordinates.forEach(x => {
        // Multiply the x-coordinate by 20 (your squares' widths)
        // and draw the rectangle at point (x, 0)
        artLayer.pathItems.rectangle(+x * 20, 0, 200, 600);
    });
    

    Now of course you might want to draw rectangles using different y coordinates as well — in that case, you can use two for-loops, splitting your CSV file first into rows (using .split('\n')) then each row into individual coordinates (using .split(',')). Then your code might look something like this:

    // Split CSV sheet into rows
    let rows = csvContents.split('\n');
    // Cycle through all the rows - in a forEach loop, the second parameter to the callback
    // is the current loop index (so in this instance, the y-coordinate)
    rows.forEach((row, y) => {
        // Split the row into individual x-coordinates
        xCoordinates = row.split(',');
        // Cycle through each x-coordinate
        xCoordinates.forEach(x => {
            // Multiply the x- and y-coordinates by 20 (your squares' widths)
            // and draw the rectangle at point (x, y)
            artLayer.pathItems.rectangle(+x * 20, y * 20, 20, 20);
        });
    });