Skip to content

Commit

Permalink
Add FitSelectionToArtboards-Lite.jsx
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Osokin committed Jul 25, 2022
1 parent 9adcb5e commit 3d33c08
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 2 deletions.
1 change: 1 addition & 0 deletions jsx/CenterClipsToArtboards.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ function main() {
// Processing clipping groups for each artboard
function processing(idx, isAlignMask, isTotal) {
selection = null;
redraw();
activeDocument.artboards.setActiveArtboardIndex(idx);
activeDocument.selectObjectsOnActiveArtboard();

Expand Down
1 change: 1 addition & 0 deletions jsx/DuplicateArtboardsLight.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ function main() {
}

selection = null;
redraw();
unlockLayers(doc.layers);
removeNote(doc.layers, CFG.lKey, CFG.hKey); // Сlear Note after previous run
saveItemsState(doc.layers, CFG.lKey, CFG.hKey);
Expand Down
2 changes: 2 additions & 0 deletions jsx/ExportToDXF.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,15 @@ function main() {

if (rbAbs.value) {
selection = null;
redraw();
for (var i = 0, abLen = absRange.length; i < abLen; i++) {
var idx = absRange[i];
var abName = doc.artboards[idx].name.replace(/\s/g, separator);
doc.artboards.setActiveArtboardIndex(idx);
doc.selectObjectsOnActiveArtboard();
exportDXF(rootDest + abName, exportOptions);
selection = null;
redraw();
}
doc.artboards.setActiveArtboardIndex(currBoardIdx);
}
Expand Down
207 changes: 207 additions & 0 deletions jsx/FitSelectionToArtboards-Lite.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/*
FitSelectionToArtboards-Lite.jsx for Adobe Illustrator
Description: Proportional resizing one selected object to fit in parent artboard
Date: July, 2022
Author: Sergey Osokin, email: hi@sergosokin.ru
Full version: https://github.com/creold/illustrator-scripts/blob/master/md/Item.md#fitselectiontoartboards
Installation: https://github.com/creold/illustrator-scripts#how-to-run-scripts
Release notes:
0.1 Initial version
Donate (optional):
If you find this script helpful, you can buy me a coffee
- via DonatePay https://new.donatepay.ru/en/@osokin
- via Donatty https://donatty.com/sergosokin
- via YooMoney https://yoomoney.ru/to/410011149615582
- via QIWI https://qiwi.com/n/OSOKIN
- via PayPal (temporarily unavailable) http://www.paypal.me/osokin/usd
NOTICE:
Tested with Adobe Illustrator CC 2018-2022 (Mac), 2022 (Win).
This script is provided "as is" without warranty of any kind.
Free to use, not for sale
Released under the MIT license
http://opensource.org/licenses/mit-license.php
Check other author's scripts: https://github.com/creold
*/

//@target illustrator
preferences.setBooleanPreference('ShowExternalJSXWarning', false); // Fix drag and drop a .jsx file

function main() {
var CFG = {
visBnds: true,
isScaleStroke: true,
isContains: true,
tag: 'artboard'
};

var isRulerTopLeft = preferences.getBooleanPreference('isRulerOriginTopLeft'),
isRulerInFourthQuad = preferences.getBooleanPreference('isRulerIn4thQuad');
CFG.isFlipY = (isRulerTopLeft && isRulerInFourthQuad) ? true : false;

if (!documents.length) {
alert('Error\nOpen a document and try again');
return;
}

if (!selection.length || selection.typename == 'TextRange') {
alert('Error\nPlease, select one item');
return;
}

var doc = app.activeDocument,
abIdx = doc.artboards.getActiveArtboardIndex(),
abBnds = doc.artboards[abIdx].artboardRect,
item = selection[0],
coord = app.coordinateSystem;

// If the active artboard contains the selected object
if (!CFG.isContains || isContains(item, CFG.tag)) {
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;

fitToArtboard(item, abBnds, CFG.visBnds, CFG.isScaleStroke);
centerToArtboard(item, abBnds, CFG.isFlipY);

app.coordinateSystem = coord;
}

selection = [item];
}

// Check if item is in the active artboard area
function isContains(item, tag) {
var isContains = false;

addTag(item, tag);

selection = null;
redraw();

activeDocument.selectObjectsOnActiveArtboard();
for (var i = 0, len = selection.length; i < len; i++) {
var item = selection[i];
if (isTagExists(item, tag)) {
isContains = true;
break;
}
}

removeTag(item, tag);

return isContains;
}

// Add custom tag to item
function addTag(item, key) {
var tag = item.tags.add();
tag.name = key;
}

// Check if item tag exists
function isTagExists(item, key) {
try {
var tag = item.tags.getByName(key);
return true;
} catch (e) {
return false;
}
}

// Remove item tag
function removeTag(item, key) {
try {
var tag = item.tags.getByName(key);
tag.remove();
} catch (e) {}
}

// Fit the item to the size of the artboard
function fitToArtboard(item, abBnds, isVisBnds, isStroke) {
var orig = item;
if (item.isType('group') && item.clipped) {
item = getMaskPath(item);
}

var bnds = isVisBnds ? item.visibleBounds : item.geometricBounds,
itemWidth = Math.abs(bnds[2] - bnds[0]),
itemHeight = Math.abs(bnds[1] - bnds[3]),
abWidth = Math.abs(abBnds[2] - abBnds[0]),
abHeight = Math.abs(abBnds[1] - abBnds[3]);

var ratioW = 100 * abWidth / itemWidth,
ratioH = 100 * abHeight / itemHeight,
ratio = Math.min(ratioW, ratioH);

// X, Y, Positions, FillPatterns, FillGradients, StrokePattern, LineWidths
orig.resize(ratio, ratio, true, true, true, true, (isVisBnds || isStroke) ? ratio : 100);
}

// Place the item in the center of the artboard
function centerToArtboard(item, abBnds, isFlipY) {
var bnds = item.geometricBounds,
itemSize = {
left: bnds[0],
top: bnds[1],
inLeft: bnds[0],
inTop: bnds[1],
inRight: bnds[2],
inBottom: bnds[3],
h: 0,
w: 0
};

if (item.isType('group') && item.clipped) {
var mask = getMaskPath(item);
bnds = mask.geometricBounds,
itemSize.inLeft = bnds[0];
itemSize.inTop = bnds[1];
itemSize.inRight = bnds[2];
itemSize.inBottom = bnds[3];
}

abWidth = Math.abs(abBnds[2] - abBnds[0]);
abHeight = Math.abs(abBnds[1] - abBnds[3]);
itemSize.h = Math.abs(itemSize.inTop - itemSize.inBottom);
itemSize.w = Math.abs(itemSize.inRight - itemSize.inLeft);

var left = itemSize.left - itemSize.inLeft,
top = itemSize.top - itemSize.inTop,
centerX = left + (abWidth - itemSize.w) / 2,
centerY = top + (itemSize.h + (isFlipY ? -1 : 1) * abHeight) / 2;

item.position = [centerX, centerY];
}

// Get the clipping mask
function getMaskPath(group) {
for (var i = 0, len = group.pageItems.length; i < len; i++) {
var currItem = group.pageItems[i];
if (isClippingPath(currItem)) {
return currItem;
}
}
}

// Check the clipping mask
function isClippingPath(item) {
var clipText = (item.isType('text') &&
item.textRange.characterAttributes.fillColor == '[NoColor]' &&
item.textRange.characterAttributes.strokeColor == '[NoColor]');
return (item.isType('compound') && item.pathItems[0].clipping) ||
item.clipping || clipText;
}

// Polyfill for checking the item typename by short name
Object.prototype.isType = function (type) {
var regexp = new RegExp(type, 'i');
return regexp.test(this.typename);
}

try {
main();
} catch (e) {}
4 changes: 3 additions & 1 deletion md/Item.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

## FitSelectionToArtboards

Places selected objects in the center of artboards and optionally fit the largest side of each object to the size of the artboard. When scaling objects, you can set internal paddings from the artboard bounds. With the `Rename artboards...` option enabled, artboards get names from the objects placed on them.
Places selected objects in the center of artboards and optionally fit the largest side of each object to the size of the artboard. When scaling objects, you can set internal paddings from the artboard bounds. With the `Rename artboards...` option enabled, artboards get names from the objects placed on them.

The Lite version (FitSelectionToArtboards-Lite.jsx) in silent mode aligns and fit one selected object to the active artboard if it is contained on it. If you edit `CFG.isContains:false` in the code, the object outside the active artboard will be placed in it.

![FitSelectionToArtboards](https://i.ibb.co/YT0qPWL/Fit-Selection-To-Artboards.gif)

Expand Down
4 changes: 3 additions & 1 deletion md/Item.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

## FitSelectionToArtboards

Раскладывает выбранные объекты по центру артбордов и опционально подгоняет размеры каждого по наибольшей стороне к размеру артборда. При масштабировании объектов можно задать внутренние отступы от границ артбордов. С включённой опцией `Rename artboards...` артборды получат пользовательские имена помещенных на них объектов.
Раскладывает выбранные объекты по центру артбордов и опционально подгоняет размеры каждого по наибольшей стороне к размеру артборда. При масштабировании объектов можно задать внутренние отступы от границ артбордов. С включённой опцией `Rename artboards...` артборды получат пользовательские имена помещенных на них объектов.

Версия Lite (FitSelectionToArtboards-Lite.jsx) без диалога выравнивает и масштабирует один выбранный объект по артборду, на котором он находится полностью или частично. Если в коде отредактировать `CFG.isContains:false`, то объект за пределами активного артборда будет помещён в него.

![FitSelectionToArtboards](https://i.ibb.co/YT0qPWL/Fit-Selection-To-Artboards.gif)

Expand Down

0 comments on commit 3d33c08

Please sign in to comment.