Copy link to clipboard
Copied
Hello —
We create in-store shelf simulations based on our design proposals.
(Proposals are created in Illustrator, but the overall simulation is done in InDesign).
Obviously, depending on products category, the shelf is more or less wide and varies according to the creation phase we are working on.
NB. I'm aware that InDesign may not be the best software to do such things, but it's what they use here at my work 😉
My question:
- - - - - - - - - - -
To avoid having to add/delete pages each time,
is there a way to use JavaScript to create an InDesign JavaScript that, when called/launched, checks the page size and increases/decreases its length depending on the length of the shelf (numbers of objects/Rectangle Frames even there is an overflow)?
Thank you for any feedback.
Enjoy your day…
- Dimitri
Hello —
IMPORTANT NOTE:
The below InDesign Javascript was developped to only impact pages from a single row (multiple pages).
Furthermore, it was developed specifically for my colleagues' request.
It is therefore NOT limited to resizing ONE page (according to the objects it contains).
It also adds some extra "white space" around the temporary "global group" since I repeat, our INDD file is a simulation of a grocery shelf, and therefore it needs to be aesthetically pleasing 😉
I have included comments
Copy link to clipboard
Copied
Copy link to clipboard
Copied
Copy link to clipboard
Copied
https://www.id-extras.com/fit-page-to-selection/
By @TᴀW
Ah yes - that's the one - couldn't find where I saw it last 😛
I use this all the time but made a few modifications for my own needs.
Copy link to clipboard
Copied
Thx, but apparently you have to pay…
I'll try my own one. 😄
Copy link to clipboard
Copied
My final Adobe InDesign Javascript, it works for me…
/**********************************************************
DESCRIPTION - V1.2 Z
BY: Dimitri Castrique aka the.bend
Resize Page to Fit All Objects
CHANGELOG V1.2:
- Force the screenmode preview to "NORMAL"
**********************************************************/
// USEFUL links: https://indisnip.wordpress.com/wp-content/uploads/2010/08/adobe-indesign-cs5-menuactions-items-list.pdf
// Path to find InDesign scripts folder: /Users/XXX/Library/Preferences/Adobe InDesign/Version 20.0/en_US/Scripts/Scripts Panel
// Main execution function
function resizePageToObjects_DC() {
if (app.documents.length === 0) {
alert("No document is open. Please open a document first.");
return;
}
// Set the view to Preview mode to hide guides and frame edges.
app.activeDocument.layoutWindows[0].screenMode = ScreenModeOptions.PREVIEW_OFF; // app.menuActions.itemByID(118829).invoke();
var doc_DC = app.activeDocument;
var activePage_DC = app.activeWindow.activePage;
var originalHorizUnits_DC = doc_DC.viewPreferences.horizontalMeasurementUnits;
var originalVertUnits_DC = doc_DC.viewPreferences.verticalMeasurementUnits;
doc_DC.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.MILLIMETERS;
doc_DC.viewPreferences.verticalMeasurementUnits = MeasurementUnits.MILLIMETERS;
// Maximize the pasteboard to prevent "leaving pasteboard" errors during the move.
try {
var maxMargin = 5000; // A very large margin in mm
doc_DC.pasteboardPreferences.pasteboardMargins = [maxMargin, maxMargin];
} catch (e_DC) {}
try {
app.activeWindow.activePage = activePage_DC;
} catch (e_DC) {}
unlockAllPages_DC(doc_DC);
overrideAllMasterPageItems_DC(doc_DC);
unlockAllLayers_DC(doc_DC);
unlockAllObjects_DC(doc_DC);
selectAllObjects_DC();
if (doc_DC.selection.length === 0) {
alert("No objects found in the document.");
doc_DC.viewPreferences.horizontalMeasurementUnits = originalHorizUnits_DC;
doc_DC.viewPreferences.verticalMeasurementUnits = originalVertUnits_DC;
return;
}
var tempGroup_DC = null;
try {
tempGroup_DC = doc_DC.groups.add(doc_DC.selection);
} catch (e_DC) {
alert("Error creating temporary group: " + e_DC.message);
doc_DC.viewPreferences.horizontalMeasurementUnits = originalHorizUnits_DC;
doc_DC.viewPreferences.verticalMeasurementUnits = originalVertUnits_DC;
return;
}
var groupBounds_DC = tempGroup_DC.visibleBounds;
var totalWidth_DC = groupBounds_DC[3] - groupBounds_DC[1];
var totalHeight_DC = groupBounds_DC[2] - groupBounds_DC[0];
if (totalWidth_DC <= 0 || totalHeight_DC <= 0) {
alert("Invalid dimensions calculated.");
try { tempGroup_DC.ungroup(); } catch (e_DC) {}
doc_DC.viewPreferences.horizontalMeasurementUnits = originalHorizUnits_DC;
doc_DC.viewPreferences.verticalMeasurementUnits = originalVertUnits_DC;
return;
}
var maxPageSize_DC = 5486.4;
var minPageSize_DC = 0.3528;
if (totalWidth_DC > maxPageSize_DC || totalHeight_DC > maxPageSize_DC || totalWidth_DC < minPageSize_DC || totalHeight_DC < minPageSize_DC) {
alert("Calculated dimensions are outside InDesign's page size limits.");
try { tempGroup_DC.ungroup(); } catch (e_DC) {}
doc_DC.viewPreferences.horizontalMeasurementUnits = originalHorizUnits_DC;
doc_DC.viewPreferences.verticalMeasurementUnits = originalVertUnits_DC;
return;
}
resizeActivePage_DC(doc_DC, totalWidth_DC, totalHeight_DC);
// Move the group to the page's top-left corner.
try {
var pageBounds_DC = activePage_DC.bounds;
var targetX_DC = pageBounds_DC[1];
var targetY_DC = pageBounds_DC[0];
tempGroup_DC.move([targetX_DC, targetY_DC], undefined, true);
} catch (e_DC) {
alert("Warning: Could not move group to origin - " + e_DC.message);
}
try {
tempGroup_DC.ungroup();
} catch (e_DC) {
alert("Warning: Could not ungroup - " + e_DC.message);
}
resizePasteboard_DC(doc_DC, totalWidth_DC, totalHeight_DC);
doc_DC.viewPreferences.horizontalMeasurementUnits = originalHorizUnits_DC;
doc_DC.viewPreferences.verticalMeasurementUnits = originalVertUnits_DC;
alert("SUCCESS!\nPage resized to:\nWidth: " + totalWidth_DC.toFixed(2) + " mm\nHeight: " + totalHeight_DC.toFixed(2) + " mm\n\nPasteboard: 120% of page size\nAll objects moved to page origin");
}
// Helper functions
function unlockAllPages_DC(doc_DC) {
var pages_DC = doc_DC.pages;
for (var i_DC = 0; i_DC < pages_DC.length; i_DC++) {
try { pages_DC[i_DC].allowPageShuffle = true; } catch (e_DC) {}
}
}
function overrideAllMasterPageItems_DC(doc_DC) {
var pages_DC = doc_DC.pages;
for (var i_DC = 0; i_DC < pages_DC.length; i_DC++) {
try {
var masterItems_DC = pages_DC[i_DC].masterPageItems;
for (var j_DC = 0; j_DC < masterItems_DC.length; j_DC++) {
try { masterItems_DC[j_DC].override(pages_DC[i_DC]); } catch (e_DC) {}
}
} catch (e_DC) {}
}
}
function unlockAllLayers_DC(doc_DC) {
var layers_DC = doc_DC.layers;
for (var i_DC = 0; i_DC < layers_DC.length; i_DC++) {
try {
layers_DC[i_DC].locked = false;
layers_DC[i_DC].visible = true;
} catch (e_DC) {}
}
}
function unlockAllObjects_DC(doc_DC) {
var allSpreads_DC = doc_DC.spreads;
for (var s_DC = 0; s_DC < allSpreads_DC.length; s_DC++) {
var spreadItems_DC = allSpreads_DC[s_DC].allPageItems;
for (var k_DC = 0; k_DC < spreadItems_DC.length; k_DC++) {
try { spreadItems_DC[k_DC].locked = false; } catch (e_DC) {}
}
}
}
function selectAllObjects_DC() {
try { app.menuActions.itemByID(276).invoke(); } catch (e_DC) {
alert("Could not invoke Select All command (ID: 276). Error: " + e_DC.message);
}
}
function resizeActivePage_DC(doc_DC, width_DC, height_DC) {
try {
doc_DC.documentPreferences.pageWidth = width_DC;
doc_DC.documentPreferences.pageHeight = height_DC;
} catch (e_DC) {
alert("Error setting page dimensions: " + e_DC.message);
}
}
function resizePasteboard_DC(doc_DC, pageWidth_DC, pageHeight_DC) {
var horizontalMargin_DC = pageWidth_DC * 0.1;
var verticalMargin_DC = pageHeight_DC * 0.1;
try {
doc_DC.pasteboardPreferences.pasteboardMargins = [verticalMargin_DC, horizontalMargin_DC];
} catch (e_DC) {
alert("Warning: Could not resize pasteboard - " + e_DC.message);
}
}
resizePageToObjects_DC();
Copy link to clipboard
Copied
Nice, but fragile. I'm quickly finding cases where it doesn't work, e.g.:
Copy link to clipboard
Copied
Hello —
IMPORTANT NOTE:
The below InDesign Javascript was developped to only impact pages from a single row (multiple pages).
Furthermore, it was developed specifically for my colleagues' request.
It is therefore NOT limited to resizing ONE page (according to the objects it contains).
It also adds some extra "white space" around the temporary "global group" since I repeat, our INDD file is a simulation of a grocery shelf, and therefore it needs to be aesthetically pleasing 😉
I have included comments on how I use it (or recommend using it)...
I made a new version, with my knowledge and help of AI,
I'm a graphic person, not a coding person…
This one fits the needs of my colleagues:
/**********************************************************
DESCRIPTION - V2.7 Z
BY: Dimitri Castrique aka the.bend
Resize Page to Fit All Objects
USAGE:
1. Select ALL.
2. Unselect ONLY what is on the page (artboard) —— or nearby.
3. DELETE what's left (ie. outside/far from the page, usually it's invisible).
4. LAUNCH the script.
CHANGELOG V2.7:
- Added 15mm extra width to the resized page
- Added functionality to ungroup the top group
- Made extra width easily configurable through a variable
**********************************************************/
// Path to find InDesign scripts folder: /Users/XXX/Library/Preferences/Adobe InDesign/Version 20.0/en_US/Scripts/Scripts Panel
// CONFIGURATION VARIABLES
var extraPageWidth_DC = 35; // Extra width to add to the page in millimeters
var targetX_DC = 10; // Target X position in millimeters
var targetY_DC = 5; // Target Y position in millimeters
function main_DC(){
if(app.documents.length > 0){
try{
// First unlock all objects on the spread
unlockAllObjects_DC();
// If nothing is selected, select all objects
if(app.documents.item(0).selection.length === 0){
selectAllObjects_DC();
}
var thing_DC = app.documents.item(0).selection;
// Store the page reference before we do anything else
var keepPage_DC = thing_DC[0].parentPage;
var keepPageName_DC = keepPage_DC.name;
var keepPageSpread_DC = keepPage_DC.parent;
sizePageToThing_DC(thing_DC);
// After resizing, select all objects and copy them
selectAllObjects_DC();
copyAllObjects_DC();
// Delete the current selection
deleteSelection_DC();
// Delete extra pages on the same row
deleteExtraPagesOnSameRow_DC(keepPageName_DC, keepPageSpread_DC);
// Paste the copied objects
pasteAllObjects_DC();
// Move the group to the target position
moveGroupToTargetPosition_DC();
// Ungroup the top group
ungroupMainTopGroup_DC();
}
catch(error_DC){
alert("Error sizing page to thing. " + error_DC.message);
}
}
else{
alert("Please open a document and try again.");
}
}
//Where "thing_DC" is an array containing one or more page items.
function sizePageToThing_DC(thing_DC){
var cornerArray_DC = getBoundsOfThing_DC(thing_DC);
var page_DC = thing_DC[0].parentPage;
// Convert extra width from mm to points
var extraWidthPoints_DC = UnitValue(extraPageWidth_DC, "mm").as("pt");
// Add extra width to the right side of the page
cornerArray_DC[1][0] = cornerArray_DC[1][0] + extraWidthPoints_DC;
//Reframe the page to the bounds of the thing with extra width.
page_DC.reframe(CoordinateSpaces.PASTEBOARD_COORDINATES, cornerArray_DC);
}
//Where "thing_DC" is an array containing one or more page items.
function getBoundsOfThing_DC(thing_DC){
var testTopLeft_DC, testBottomRight_DC;
//Get the initial bounds of the object. If there's only one object in the array, this is all we'll need.
var topLeft_DC = thing_DC[0].resolve(AnchorPoint.TOP_LEFT_ANCHOR, CoordinateSpaces.PASTEBOARD_COORDINATES)[0];
var bottomRight_DC = thing_DC[0].resolve(AnchorPoint.BOTTOM_RIGHT_ANCHOR, CoordinateSpaces.PASTEBOARD_COORDINATES)[0];
if(thing_DC.length > 1){
for(var counter_DC = 1; counter_DC < thing_DC.length; counter_DC++){
testTopLeft_DC = thing_DC[counter_DC].resolve(AnchorPoint.TOP_LEFT_ANCHOR, CoordinateSpaces.PASTEBOARD_COORDINATES)[0];
testBottomRight_DC = thing_DC[counter_DC].resolve(AnchorPoint.BOTTOM_RIGHT_ANCHOR, CoordinateSpaces.PASTEBOARD_COORDINATES)[0];
if(testTopLeft_DC[0] < topLeft_DC[0]){
topLeft_DC[0] = testTopLeft_DC[0];
}
if(testTopLeft_DC[1] < topLeft_DC[1]){
topLeft_DC[1] = testTopLeft_DC[1];
}
if(testBottomRight_DC[0] > bottomRight_DC[0]){
bottomRight_DC[0] = testBottomRight_DC[0];
}
if(testBottomRight_DC[1] > bottomRight_DC[1]){
bottomRight_DC[1] = testBottomRight_DC[1];
}
}
}
return new Array(topLeft_DC, bottomRight_DC);
}
function unlockAllObjects_DC() {
try {
// First try with the suggested ID 11395
app.menuActions.itemByID(11395).invoke();
} catch (e_DC) {
try {
// If that doesn't work, try the direct property approach
app.activeDocument.pageItems.everyItem().locked = false;
} catch (e2_DC) {
alert("Could not unlock all objects. Error: " + e2_DC.message);
}
}
}
function selectAllObjects_DC() {
try {
app.menuActions.itemByID(276).invoke();
// Try to group all selected objects using multiple methods
try {
// First try the menu action
app.menuActions.itemByID(118844).invoke();
} catch (e_DC) {
try {
// If that fails, try alternative menu action IDs
app.menuActions.itemByID(11903).invoke();
} catch (e2_DC) {
try {
// If that fails, try to group using the DOM
var selection_DC = app.activeDocument.selection;
if (selection_DC.length > 1) {
app.activeDocument.groups.add(selection_DC);
}
} catch (e3_DC) {
// If all methods fail, continue without grouping
// Grouping is not essential for the script to work
}
}
}
} catch (e_DC) {
alert("Could not invoke Select All command (ID: 276). Error: " + e_DC.message);
}
}
function copyAllObjects_DC() {
try {
app.menuActions.itemByID(270).invoke();
} catch (e_DC) {
alert("Could not invoke Copy command (ID: 270). Error: " + e_DC.message);
}
}
function deleteSelection_DC() {
try {
// First try to clear all objects on the current spread
var currentSpread_DC = app.activeWindow.activeSpread;
var allPageItems_DC = currentSpread_DC.allPageItems;
// Delete all page items in reverse order to avoid index issues
for (var i_DC = allPageItems_DC.length - 1; i_DC >= 0; i_DC--) {
try {
allPageItems_DC[i_DC].remove();
} catch (e2_DC) {
// If we can't remove an item, try the menu action approach
try {
app.menuActions.itemByID(290).invoke();
} catch (e3_DC) {
try {
app.menuActions.itemByID(291).invoke();
} catch (e4_DC) {
// Last resort - try to remove the selection directly
var selection_DC = app.activeDocument.selection;
for (var j_DC = selection_DC.length - 1; j_DC >= 0; j_DC--) {
selection_DC[j_DC].remove();
}
}
}
}
}
} catch (e_DC) {
alert("Could not delete selection. Error: " + e_DC.message);
}
}
function pasteAllObjects_DC() {
try {
app.menuActions.itemByID(271).invoke();
} catch (e_DC) {
alert("Could not invoke Paste command (ID: 271). Error: " + e_DC.message);
}
}
function moveGroupToTargetPosition_DC() {
try {
// Select all objects to ensure we have the pasted group
app.menuActions.itemByID(276).invoke();
// Get the bounds of the selection
var selection_DC = app.activeDocument.selection;
if (selection_DC.length > 0) {
// Get the current position
var bounds_DC = selection_DC[0].geometricBounds;
var currentX_DC = bounds_DC[1];
var currentY_DC = bounds_DC[0];
// Convert target positions from mm to points
var targetXPoints_DC = UnitValue(targetX_DC, "mm").as("pt");
var targetYPoints_DC = UnitValue(targetY_DC, "mm").as("pt");
// Calculate how much to move
var moveX_DC = targetXPoints_DC - currentX_DC;
var moveY_DC = targetYPoints_DC - currentY_DC;
// Move all selected objects
for (var i_DC = 0; i_DC < selection_DC.length; i_DC++) {
selection_DC[i_DC].move(undefined, [moveX_DC, moveY_DC]);
}
}
} catch (e_DC) {
alert("Could not move group to target position. Error: " + e_DC.message);
}
}
function ungroupMainTopGroup_DC() {
try {
app.menuActions.itemByID(118845).invoke();
} catch (e_DC) {
try {
// If the menu action fails, try to ungroup using the DOM
var selection_DC = app.activeDocument.selection;
for (var i_DC = selection_DC.length - 1; i_DC >= 0; i_DC--) {
if (selection_DC[i_DC].constructor.name === "Group") {
selection_DC[i_DC].ungroup();
}
}
} catch (e2_DC) {
alert("Could not invoke Ungroup command (ID: 118845). Error: " + e2_DC.message);
}
}
}
function deleteExtraPagesOnSameRow_DC(keepPageName_DC, keepPageSpread_DC) {
try {
var doc_DC = app.documents.item(0);
var allPages_DC = doc_DC.pages;
// Find the page to keep by name
var keepPage_DC = null;
for (var i_DC = 0; i_DC < allPages_DC.length; i_DC++) {
if (allPages_DC[i_DC].name === keepPageName_DC) {
keepPage_DC = allPages_DC[i_DC];
break;
}
}
// If we couldn't find the page to keep, exit
if (keepPage_DC === null) {
alert("Could not find the page to keep. Aborting page deletion.");
return;
}
// Get all pages in the same spread as the page to keep
var pagesInSameSpread_DC = keepPageSpread_DC.pages;
// Collect pages to delete (all pages in the same spread except the one to keep)
var pagesToDelete_DC = [];
for (var j_DC = 0; j_DC < pagesInSameSpread_DC.length; j_DC++) {
var currentPage_DC = pagesInSameSpread_DC[j_DC];
// If it's not the page to keep, add to delete list
if (currentPage_DC.name !== keepPageName_DC) {
pagesToDelete_DC.push(currentPage_DC);
}
}
// Delete the pages (in reverse order to avoid index issues)
for (var k_DC = pagesToDelete_DC.length - 1; k_DC >= 0; k_DC--) {
try {
// First try to clear all objects on the page
var pageItems_DC = pagesToDelete_DC[k_DC].allPageItems;
for (var l_DC = pageItems_DC.length - 1; l_DC >= 0; l_DC--) {
pageItems_DC[l_DC].remove();
}
// Then remove the page
pagesToDelete_DC[k_DC].remove();
} catch (e_DC) {
// If we can't delete the page directly, try to remove it through the document
try {
doc_DC.pages.itemByName(pagesToDelete_DC[k_DC].name).remove();
} catch (e2_DC) {
// As a last resort, try to move the page to a temporary location and then delete
try {
var tempPage_DC = doc_DC.pages.add();
pagesToDelete_DC[k_DC].move(LocationOptions.AFTER, tempPage_DC);
tempPage_DC.remove();
pagesToDelete_DC[k_DC].remove();
} catch (e3_DC) {
alert("Could not delete page: " + pagesToDelete_DC[k_DC].name + ". Error: " + e3_DC.message);
}
}
}
}
} catch (e_DC) {
alert("Error deleting extra pages: " + e_DC.message);
}
}
function getPagesPerRow_DC(doc_DC) {
try {
// Try to determine pages per row from document preferences
// This is a simplified approach - you may need to adjust based on your document setup
var pageWidth_DC = doc_DC.documentPreferences.pageWidth;
var pageHeight_DC = doc_DC.documentPreferences.pageHeight;
var facingPages_DC = doc_DC.documentPreferences.facingPages;
// If facing pages are enabled, assume 2 pages per row
if (facingPages_DC) {
return 2;
} else {
// For single pages, we need to determine the layout
// This is a simplified approach - you might need to adjust based on your specific document setup
var spreadCount_DC = doc_DC.spreads.length;
var pageCount_DC = doc_DC.pages.length;
// Calculate average pages per spread
return Math.round(pageCount_DC / spreadCount_DC);
}
} catch (e_DC) {
// Default to 1 if we can't determine
return 1;
}
}
main_DC();Copy link to clipboard
Copied
Hi @dimitri_cas , I might be missing what you want the script to do, but yours also breakes for me. I get this error:
Not sure it needs to be so complex—this transforms the page to the page items bounds:
//Set Page Size to the active page’s objects
//use point for page resize
app.scriptPreferences.measurementUnit = MeasurementUnits.POINTS;
var d = app.activeDocument;
d.zeroPoint = [0, 0];
var p = app.activeWindow.activePage
var api = p.pageItems;
var tg;
if (api.length == 1) {
tg = api[0]
} else {
//group page items to get bounds—moves everything to top layer, is that OK?
tg = d.groups.add(api);
}
//get the groups width and height
var b = tg.geometricBounds;
var h = b[2] - b[0]
var w = b[3] - b[1]
//resize the page
p.resize (CoordinateSpaces.INNER_COORDINATES,AnchorPoint.CENTER_ANCHOR,ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH,[w,h])
tg.move([0,0])
app.scriptPreferences.measurementUnit = AutoEnum.AUTO_VALUE;
Copy link to clipboard
Copied
Hey rob 🙂
Thanks for your reply.
Indeed, you don't have the full context.
My colleagues are working with something like 10 pages distributed on 3 rows.
Some of these pages overlap, they come from different “parent” pages, …
So it's definitely not just one page that needs to be resized 😉
But thanks for your time.
- Dimitri
Find more inspiration, events, and resources on the new Adobe Community
Explore Now