Artboard To Selection

Script for Adobe Illustrator

Size the artboard around selected art with a specified margin.

  • Set margin
  • Choose measurement units
  • Adapt open source to customize or create other scripts
Download
Artboard To Selection

FREE to download
Please make a contribution

Many scripts are free to download thanks to the support of users. Help me keep developing new scripts by supporting my work. Click the button to make a contribution of any amount. Thank you.

How-to Video

How to use the script

The interface is a single input for the desired margin. Choose the measurement units in the drop-down list to the right. Click the OK button, and the artboard is changed to the size of the selection plus the margin value on all sides.

Source code

(download button below)

/*

Artboard To Selection
Copyright 2022 William Campbell
All Rights Reserved
https://www.marspremedia.com/contact

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

*/

(function () {

    var defaults = {
        margin: 0.125,
        // units: "Pixels"
        // units: "Points"
        // units: "Picas"
        units: "Inches"
        // units: "Millimeters"
        // units: "Centimeters"
    };

    var title = "Artboard To Selection";

    if (!/illustrator/i.test(app.name)) {
        alert("Script for Illustrator", title, false);
        return;
    }

    // Script variables.
    var doc;
    var measurementUnits;
    var measurementUnitsShort;

    // Reusable UI variables.
    var g; // group
    var p; // panel
    var w; // window

    // Permanent UI variables.
    var btnCancel;
    var btnOk;
    var inpMargin;
    var listUnits;

    // SETUP

    measurementUnits = [
        "Pixels",
        "Points",
        "Picas",
        "Inches",
        "Millimeters",
        "Centimeters"
    ];
    measurementUnitsShort = [
        "px",
        "pt",
        "pc",
        "in",
        "mm",
        "cm"
    ];

    // Script requires open document.
    if (!app.documents.length) {
        alert("Open a document", title, false);
        return;
    }
    doc = app.activeDocument;
    // Need at least one element selected.
    if (!doc.selection[0]) {
        alert("Select something", title, false);
        return;
    }
    // Script doesn't work in Isolation Mode.
    if (doc.layers[0].name == "Isolation Mode") {
        alert("Exit Isolation Mode before running script", title, false);
        return;
    }

    // CREATE USER INTERFACE

    w = new Window("dialog", title);
    w.alignChildren = "fill";
    // Panel.
    p = w.add("panel");
    p.alignChildren = "left";
    g = p.add("group");
    g.add("statictext", undefined, "Margin:");
    inpMargin = g.add("edittext");
    inpMargin.preferredSize = [50, -1];
    listUnits = g.add("dropdownlist", undefined, measurementUnits);
    listUnits.preferredSize = [100, -1];

    // Action Buttons.
    g = w.add("group");
    g.alignment = "center";
    btnOk = g.add("button", undefined, "OK");
    btnCancel = g.add("button", undefined, "Cancel");
    // Panel Copyright.
    p = w.add("panel");
    p.add("statictext", undefined, "Copyright 2022 William Campbell");

    // SET DEFAULT VALUES
    // MUST PRECEDE UI EVENT HANDLERS SO THEY DON'T FIRE WHILE SETTING VALUES

    inpMargin.text = defaults.margin;
    listUnits.selection = listUnits.find(defaults.units) || 0;
    listUnits.priorIndex = listUnits.selection.index;

    // UI ELEMENT EVENT HANDLERS

    inpMargin.onChange = function () {
        validateFloat(this);
    };

    listUnits.onChange = function () {
        var index;
        var mu1;
        var mu2;
        var convert = function (uiEdit) {
            if (/,/.test(uiEdit.text)) {
                // Has comma: appears decimal comma.
                // Replace comma with point, then restore comma.
                uiEdit.text = String(parseFloat(UnitValue(Number(uiEdit.text.replace(",", ".")), mu1).as(mu2).toFixed(4))).replace(".", ",");
            } else {
                // Default: decimal point.
                uiEdit.text = String(parseFloat(UnitValue(Number(uiEdit.text), mu1).as(mu2).toFixed(4)));
            }
        };
        index = this.selection.index;
        if (index != this.priorIndex) {
            // Units have changed.
            mu1 = measurementUnitsShort[this.priorIndex];
            mu2 = measurementUnitsShort[index];
            convert(inpMargin);
        }
        this.priorIndex = index;
    };

    btnOk.onClick = function () {
        w.close(1);
    };

    btnCancel.onClick = function () {
        w.close(0);
    };

    // DISPLAY THE DIALOG

    if (w.show() == 1) {
        try {
            process();
        } catch (e) {
            alert("An error has occurred.\nLine " + e.line + ": " + e.message, title, true);
        }
    }

    //====================================================================
    //               END PROGRAM EXECUTION, BEGIN FUNCTIONS
    //====================================================================

    function process() {
        var artboard;
        var docScaleFactor;
        var i;
        var padding;
        var tb;
        var vb;
        docScaleFactor = doc.scaleFactor || 1;
        padding = valueAsPoints(inpMargin, listUnits) / docScaleFactor;
        vb = doc.selection[0].visibleBounds;
        for (i = 1; i < doc.selection.length; i++) {
            tb = doc.selection[i].visibleBounds;
            vb[0] = Math.min(vb[0], tb[0]);
            vb[1] = Math.max(vb[1], tb[1]);
            vb[2] = Math.max(vb[2], tb[2]);
            vb[3] = Math.min(vb[3], tb[3]);
        }
        artboard = doc.artboards[doc.artboards.getActiveArtboardIndex()];
        artboard.artboardRect = [
            vb[0] - padding,
            vb[1] + padding,
            vb[2] + padding,
            vb[3] - padding
        ];
    }

    function validateFloat(uiEdit) {
        var s;
        var v;
        // Remove non-digits.
        s = uiEdit.text.replace(/[^0-9.]/g, "");
        if (s != uiEdit.text) {
            alert("Numeric input only.\nNon-numeric characters removed.", " ", false);
        }
        // No more than one decimal point.
        s = s.replace(/\.{2,}/g, ".");
        v = parseFloat(s) || 0;
        uiEdit.text = v.toString();
    }

    function valueAsPoints(uiEdit, uiList) {
        var mu;
        var v;
        mu = measurementUnitsShort[uiList.selection.index];
        v = parseFloat(uiEdit.text) || 0;
        return UnitValue(v, mu).as("pt");
    }

})();
Many scripts are free to download thanks to the support of users. Help me keep developing new scripts by supporting my work. Click the button to make a contribution of any amount. Thank you.
Download
Artboard To Selection

For help installing scripts, see How to Install and Use Scripts in Adobe Creative Cloud Applications.

Also available for hire to program custom solutions. Contact William for more information.

IMPORTANT: by downloading any of the scripts on this page you agree that the software is provided without any warranty, express or implied. USE AT YOUR OWN RISK. Always make backups of important data.