Script to automatically snap all points to grid in Adobe Illustrator?

How would you write a script to move all points of all selected paths to the nearest (non-pixel grid) grid point?

Sample before and after alignment

e.g. I want all of the points of each polygon/path to snap to the nearest point on a custom grid. Mine is setup as 1 grid unit = 11.338px or 4mm, but ideally the script would extend to any unit value


// set grid units as pixels - in my case 11.338px = 8mm = 1 grid unit

units = 11.338 

// Nested loop through all polygons/paths, then all points in each polygon

For each Polygon {

    For each Point P in Polygon {

    // move the Point x, y to the nearest grid point in units
        P.x = units * Round(P.x/units) 
        P.y = units * Round(P.y/units)

Does this make sense? It’s been a while since I’ve done any programming.
I’ve also never scripted for Illustrator, so not exactly sure how to implement this.

LINK: I’ve looked at the post by @KromStern but not sure how to implement based on that thread. How to align all selected points to a grid?


Here you go, make sure the paths that you want to snap are selected:

  // jooSnapToDocumentGrid.jsx

#target illustrator


function main(){
    var grid = getDocumentGrid();
    snapSelectedPathToDocumentGrid(activeDocument.selection, grid); 

function snapSelectedPathToDocumentGrid(sel, grid){
    for(var i = 0; i < sel.length; i++){
        try {
            var pp = sel[i].pathPoints;
            for(var j = 0; j < pp.length; j++){
                var p = pp[j];
                p.leftDirection = nearestGrid(p.leftDirection, grid);
                p.rightDirection = nearestGrid(p.rightDirection, grid);
                p.anchor = nearestGrid(p.anchor, grid);       
        } catch(err) { }

function getDocumentGrid(){
    var prf = app.preferences;
    var ticks = prf.getIntegerPreference('Grid/Horizontal/Ticks');
    var spacing = prf.getRealPreference('Grid/Horizontal/Spacing');
    return spacing/ticks;    

function nearestGrid(anchor, grid) {
    return [Math.round(anchor[0] / grid) * grid, 
            Math.round(anchor[1] / grid) * grid ];

Source : Link , Question Author : Johnnystackexchange , Answer Author : joojaa

Leave a Comment