Site logo

Transforming page items

Instead of using geometricBounds property now and then, you can use reframe method. Here is an example:

var frame = app.selection[0];
var page = app.documents[0].pages[0];
var pBounds = page.bounds;
$.writeln("pBounds: " + pBounds); // => pBounds: 0,0,792,612
var topLeft = page.resolve(AnchorPoint.TOP_LEFT_ANCHOR,CoordinateSpaces.SPREAD_COORDINATES)[0];
var bottomRight = page.resolve(AnchorPoint.BOTTOM_RIGHT_ANCHOR,CoordinateSpaces.SPREAD_COORDINATES)[0];
$.writeln("topLeft: " + topLeft+" bottomRight: "+bottomRight);
var corners = [topLeft,bottomRight];
frame.reframe(CoordinateSpaces.SPREAD_COORDINATES, corners);

Note that resolve() wraps up the provided corner coordinates in doubly nested arrays, thus the [0] dereference.
Below ia an example that also considers margin preferences.

var myPage = app.documents[0].pages[0];
var pageBounds = myPage.bounds;
var pageWidth = pageBounds[3] - pageBounds[1];
var pageHeight = pageBounds[2] - pageBounds[0];
var mTop = myPage.marginPreferences.top / pageHeight;
var mBottom =1 - myPage.marginPreferences.bottom / pageHeight;
var mLeft = myPage.marginPreferences.left / pageWidth;
var mRight = 1 - myPage.marginPreferences.right / pageWidth;
var mySpread = myPage.parent;
var myFrame = mySpread.textFrames.add();
var topLeft = myPage.resolve(
  [[mLeft, mTop], BoundingBoxLimits.GEOMETRIC_PATH_BOUNDS],
  CoordinateSpaces.SPREAD_COORDINATES)[0];
var bottomRight = myPage.resolve(
  [[mRight, mBottom], BoundingBoxLimits.GEOMETRIC_PATH_BOUNDS],
  CoordinateSpaces.SPREAD_COORDINATES)[0];
myFrame.reframe( CoordinateSpaces.SPREAD_COORDINATES, [topLeft, bottomRight]);

Function setWidthHeight by Marc

    function setWidthHeight(/*PageItem*/o, /*str*/w, /*str*/h, /*bool=false*/useVisibleBounds)
{
    if( !o.resize ) return;
    
    var CS_INNER = CoordinateSpaces.INNER_COORDINATES,
        BB = BoundingBoxLimits[(useVisibleBounds?'OUTER_STROKE':'GEOMETRIC_PATH') + '_BOUNDS'];
    
    var wPt = UnitValue(w).as('pt'),
        hPt = UnitValue(h).as('pt');
    
    if( 0 >= wPt || 0 >= hPt ) return;
    
    o.resize(
        [CS_INNER,BB],
        AnchorPoint.CENTER_ANCHOR,
        ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH,
        [wPt,hPt,CS_INNER]
        );
}
 
// Sample code
// ---
setWidthHeight(app.selection[0], "5cm", "50pt");
    

Flatten the transformations of the selection