9 Replies Latest reply on Jun 18, 2015 3:18 AM by sethkhouri

    Adding a function to

    sethkhouri

      Hi

       

      I am not very experienced with java and I thought that i would play with something in my free time, this has become an obsession and now I am going a little crazy.

       

      I found an exist script that had some modifications done to it then tried to add in a few of my own things,

      This is doing what I need it to do except for one thing that I couldn't do, until i realized I was doing it wrong (well i think)

      I have an existing file name BTAS8234_P14-20 New.indd its a page filled with Text and Images.

      I want to put a label on each image box with part of the file name, the actual page number the image is on and a number. so the the label would end up looking like 8234_14_001 (for page 14) or 8235_15_001 (for page 15)

      I got some help with some very nice people and this is what I was using this to create the label myLabel = myDocument.properties.name.replace(/\D+/,'').split(' ')[0].split('_')[0]+'_' +app.activeWindow.activePage.name+'_'+padNumber(myCounter);

      I thought the issue was that it was with the above.. But now i am thinking its more to do with one of the functions (line 128) so I thought and I may be way off the mark, of writing in a new function to Get a count of all pages in the document. (i started writing this line 121 but I raelly don't know what i am doing)

      then with the function on Line 128 changing it so that it goes through allGraphics on each page in the order from first to last.

       

      I am not sure if i am on the right track or not, but any help would be greatly appreciated.

       

      Thank you

       


      //LabelGraphics.jsx (Modified)
      //An InDesign CS3 JavaScript
      /* 
      @@@BUILDINFO@@@ "LabelGraphics.jsx" 1.1.0 6-June-2008
      */
      //Adds labels to the graphics in the active document.
      /* This sample script has been modified. The modications are listed here: option added to create a label from clipboard data,
        dropdown menu added to apply a swatch to the caption frame. This script can now apply lables to just the selected graphics
        if you have one or more images selected. Otherwise it will apply the lables to all graphics in the document. The hieght of the
        caption frame is determined by the amount of text, and paragraph style applied. the width of the caption frame is
        determined by the width of the graphic it is under. Setting the caption height in the dialog box has been removed, as it is no
        longer needed.
        */
      main();
      
      
      //=============================================================\\
      function main(){
      // Make sure the swatch "ImageGreen" exists
        try {
          app.activeDocument.colors.add({name:"ImageLabel", space:ColorSpace.CMYK, colorValue:[0,0,100,0], colorModel:ColorModel.PROCESS});
        } catch (_) { }
        LabelYellow = app.activeDocument.swatches.item("ImageLabel");
          // Make sure the paragraph style "ImageSize" exists
        try {
          app.activeDocument.paragraphStyles.add({name:"ImageLabel", appliedFont:"Arial\tRegular", pointSize:9, justification: Justification.CENTER_ALIGN});
        } catch (_) { }
        reportStyle = app.activeDocument.paragraphStyles.item("ImageLabel");
      }
      
      
      firstStart();
      //=============================================================\\
      function firstStart(){
        if(app.documents.length != 0){
        if(app.documents.item(0).allGraphics.length != 0){
        myDisplayDialog();
        }
        else{
        alert("Document contains no graphics.");
        }
        }
        else{
        alert("Please open a document and try again.");
        }
      }
      
      
      //=============================================================\\
      function myDisplayDialog(){
        var myLabelWidth = 100;
        var myStyle = app.activeDocument.paragraphStyles.item("ImageLabel");
        var mySwatch = app.activeDocument.swatches.item("ImageLabel");
        var myDialog = app.dialogs.add({name:"Label Graphics"});
        with(myDialog.dialogColumns.add()){
        //Label type
        with(dialogRows.add()){
        with(dialogColumns.add()){
        staticTexts.add({staticLabel:"Label Type", minWidth:myLabelWidth});
        }
        with(dialogColumns.add()){
        var myLabelTypeDropdown = dropdowns.add({stringList:["Image Name","Image File Name", "Image File Path", "XMP Description", "XMP Author","Paste from clipboard"], selectedIndex:0});
        }
        }
        with(dialogRows.add()){
        with(dialogColumns.add()){
        staticTexts.add({staticLabel:"Label Offset", minWidth:myLabelWidth});
        }
        with(dialogColumns.add()){
        var myLabelOffsetField = measurementEditboxes.add({editValue:0});
        }
        }
        }
      
      
      
      
      //=============================================================\\
        var myResult = myDialog.show();
        if(myResult == true){
        var myLabelType = myLabelTypeDropdown.selectedIndex;
        var myLabelHeight = 14.173; // A generic label height that will be adjusted later
        myPasteFailure = false;
        var myLabelOffset = myLabelOffsetField.editValue;
        var myStyle = app.activeDocument.paragraphStyles.item("ImageLabel");
        var mySwatch = app.activeDocument.swatches.item("ImageLabel");
        myDialog.destroy();
        var myOldXUnits = app.documents.item(0).viewPreferences.horizontalMeasurementUnits;
        var myOldYUnits = app.documents.item(0).viewPreferences.verticalMeasurementUnits;
        app.documents.item(0).viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
        app.documents.item(0).viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
      
      
        try{
        myAddLabels(myLabelType, myLabelHeight, myLabelOffset, myStyle, mySwatch);
        }
        catch(e){
        alert("Unable to add lables. " + e);
        }
      
        try{
        resizeOverset() ;
        }
        catch(e){
        alert("Unable to correct overset text. " + e);
        }
      
        if (myPasteFailure == true){
        alert("Unable to paste from clipboard.");
        }
      
        app.documents.item(0).viewPreferences.horizontalMeasurementUnits = myOldXUnits;
        app.documents.item(0).viewPreferences.verticalMeasurementUnits = myOldYUnits;
        }
        else{
        myDialog.destroy();
        }
      }
      
      
      //=============================================================\\
      function getAllPages();
      var getAllPages = myOpenDocument.Pages.length;
      
      
      
      
      //=============================================================\\
      function myAddLabels(myLabelType, myLabelHeight, myLabelOffset, myStyle, mySwatch){
        var myDocument = app.activeDocument.item(0);
        myStoriesArray = new Array();
      
        if (app.selection.length == 0) // If nothing is selected apply caption to all graphics in the document
        {
        var myConfirmation = confirm("Add captions to all images in the document?", false, "LabelGraphics.jsx" );
        if (myConfirmation == true)
        {
        var myGraphics = myDocument.allGraphics;
        }
        }
        else
        { // If graphics are selected, just add captions to the selected items, as long as they are rectangles(image frames)
        var myConfirmation = true;
        var mySelections = app.selection;
        myGraphics = new Array();
      
        for(i = 0; i < mySelections.length; i++){
        if(mySelections[i] == "[object Rectangle]"){  //Check to make sure selection only includes rectangles
        myGraphics.push(mySelections[i].allGraphics[0]);
        }
        else{
        //alert("Objects other than graphics were selected!");
        //Nothing happens if you don't select at least one graphic
        }
        }
        }
      
        var myStyle = app.activeDocument.paragraphStyles.item("ImageLabel");
        mySwatch = myDocument.swatches.item("ImageLabel");
      
        if (myConfirmation == true){
        for(var myCounter = 1; myCounter < myGraphics.length; myCounter++){
        try{
        myAddLabel(myDocument, myGraphics[myCounter], myCounter, myLabelType, myLabelHeight, myLabelOffset, myStyle, mySwatch, myStoriesArray);
        }
        catch(e){};
        }
        }
      }
      
      
      //=============================================================\\
      
      
      
      
      //=============================================================\\
      function myAddLabel(myDocument, myGraphic, myCounter, myLabelType, myLabelHeight, myLabelOffset, myStyle, mySwatch, myStoriesArray){
        var myLabel;
        var myLink = myGraphic.itemLink;
        var myPasteFromClipboard = false;
        //Create the label layer if it does not already exist.
        var myLabelLayer = myDocument.layers.item("Coded Layout");
        try{
        myLabelLayer.name;
        }
        catch (myError){
        myLabelLayer = myDocument.layers.add({name:"Coded Layout"});
        }
        //Label type defines the text that goes in the label.
        switch(myLabelType){
      //File name
        case 0:
        myLabel = myDocument.properties.name.replace(/\D+/,'').split(' ')[0].split('_')[0]+'_' + app.activeWindow.activePage.name+'_'+padNumber(myCounter);
        break;
              //Image name
        case 1:
        myLabel = myLink.name;
        break;
        //Image File path
        case 2:
        myLabel = myLink.filePath;
        break;
        //XMP description
        case 3:
        try{
        myLabel = myLink.linkXmp.description;
        }
        catch(myError){
        myLabel = "No description available.";
        }
        break;
        //XMP author
        case 3:
        try{
        myLabel = myLink.linkXmp.author
        }
        catch(myError){
        myLabel = "No author available.";
        }
        break;
        //Paste from the clipboard
        case 4:
        try{
        myPasteFromClipboard = true;
        }
        catch(myError){
        myLabel = "No clipboard data available.";
        }
        break;
        }
        var myFrame = myGraphic.parent;
        myX1 = myFrame.geometricBounds[1];
        myY1 = myFrame.geometricBounds[2] + myLabelOffset;
        myX2 = myFrame.geometricBounds[3];
        myY2 = myY1 + myLabelHeight;
      
        if (myPasteFromClipboard ==true)
        {
        try{
        var myTextFrame = myFrame.parent.textFrames.add(myLabelLayer, undefined, undefined,{geometricBounds:[myY1, myX1, myY2, myX2]});
        myTextFrame.insertionPoints.item(0).select();
        app.paste();
        }
        catch(e){
        myTextFrame.remove();
        myPasteFailure = true;
        }
        }
        else{
        var myTextFrame = myFrame.parent.textFrames.add(myLabelLayer, undefined, undefined,{geometricBounds:[myY1, myX1, myY2, myX2], contents:myLabel});
        }
      
        myTextFrame.textFramePreferences.firstBaselineOffset = FirstBaseline.leadingOffset;
        myTextFrame.paragraphs.item(0).appliedParagraphStyle = myStyle;
      
      
      
        myTextFrame.fillColor = mySwatch;
        myFrameParentStory = myTextFrame.parentStory;
        myStoriesArray.push(myFrameParentStory);
      
      }
      
      
      
      
      
      
      //=============================================================\\
      function myGetParagraphStyleNames(){
        var myStyle = app.activeDocument.paragraphStyles.item("ImageLabel");
        return myStyle;
      }
      
      
      function myGetSwatchNames(){
        var mySwatch = app.activeDocument.swatches.item("ImageLabel");
        return mySwatch;
      }
      
      
      function padNumber(number) {
        if (number<=9999) { number = ("000"+number).slice(-3); }
        return number;
      }
      
      
      function resizeOverset() {
                  for (var j = myStoriesArray.length - 1; j >= 0; j--) {
                          myLastFrame = myStoriesArray[j].texts[0].parentTextFrames[myStoriesArray[j].texts[0].parentTextFrames.length - 1];
                         
        myNewY2 = myLastFrame.geometricBounds[3]; //get the width of the text frame before doing fit()
      
        myLastFrame.fit(FitOptions.CENTER_CONTENT);
      
        myNewY1 = myLastFrame.geometricBounds[1];
        myNewX1 = myLastFrame.geometricBounds[2];
        myNewX2 = myLastFrame.geometricBounds[0];
      
      
        myLastFrame.geometricBounds = [myNewX1, myNewY1, myNewX2, myNewY2]; // reset the width to before fit() was ran
      
      
                  }
              }
      
      
        • 1. Re: Adding a function to
          Marc Autret Level 4

          Hi,

           

          The original code has too many issues. Best is to give it up (IMHO) and try something new.

           

          // LabelGraphics revisited for InDesign CS6/CC
          // Draft version (5-Jun-15)
          
          
          // =====================================
          // YOUR SETTINGS
          // =====================================
          
          const LAYER_PROPS = {
              name:          "Coded Layout",
              };
          
          const COLOR_PROPS = {
              name:          "ImageLabel",
              space:         +ColorSpace.CMYK,
              colorValue:    [0,0,100,0],
              colorModel:    +ColorModel.PROCESS,
              };
          
          const FRAME_PROPS = {
              textFramePreferences: {firstBaselineOffset: +FirstBaseline.leadingOffset},
              fillColor: COLOR_PROPS.name,
              };
          
          const STYLE_PROPS = {
              name:          "ImageLabel",
              appliedFont:   "Myriad Pro\tRegular",
              pointSize:     9,
              justification: +Justification.CENTER_ALIGN
              };
          
          // =====================================
          // UTILITIES
          // =====================================
          
          const MU_POINTS = +MeasurementUnits.points;
          
          const VIEW_PREFS_POINTS = {
              horizontalMeasurementUnits: MU_POINTS,
              verticalMeasurementUnits: MU_POINTS,
              };
          
          var getValidGraphics = function(/*?DOM[]*/sel,  r,i,t)
          // -------------------------------------
          // Ret. the array of *valid* graphics found in sel.
          // (If no item is found, return zero.)
          // An item is considered valid if it has an itemLink
          // property and belongs to a Rectangle.
          {
              if( !sel || !(i=sel.length) ) return 0;
              
              r = [];
              while( i-- )
                  {
                  t = sel[i];
          
                  // If the current item is a Rectangle frame and contains
                  // at least a graphic, consider the first graphic found.
                  // ---
                  if( t instanceof Rectangle )
                      {
                      if( !(t=t.allGraphics).length ) continue;
                      t = t[0];
                      }
          
                  // If the considered item *is* a Graphic, make sure its
                  // parent container is a Rectangle, then push.
                  // ---
                  if( 'itemLink' in t && t.parent instanceof Rectangle )
                      {
                      r.push(t);
                      }
                  }
          
              return r.length && r;
          };
          
          var getClipboardText = function(  r,t,doc,r,sto,ma)
          // -------------------------------------
          // Ret. the string content of the clipboard, if possible.
          // Otherwise, return 0.
          {
              // Default returned value.
              r = 0;
          
              // Hide the process.
              // ---
              (t=app.scriptPreferences.enableRedraw) && (app.scriptPreferences.enableRedraw=false);
          
              // Create a temp doc...
              // ---
              doc = app.documents.add();
              sto = doc.textFrames.add().parentStory;
              sto.insertionPoints[0].select();
              
              // Try to paste.
              // ---
              if( (ma=app.menuActions.itemByName("$ID/Paste")).isValid && ma.enabled )
                  {
                  try{ app.paste() }catch(_){}
                  r = sto.texts[0].contents;
                  }
              
              // Cleanup and return.
              // ---
              doc.close(SaveOptions.NO);
              t && (app.scriptPreferences.enableRedraw=t);
              return r || 0;
          };
          
          var parentSpread = function F(/*DOM*/o,  p)
          //--------------------------------------
          {
              p = o && o.parent; // don't use o.properties.parent [CS6 bug]
          
              if( (!p) || (p instanceof Document) ) return null;
              
              return ( (p instanceof Spread) || (p instanceof MasterSpread) ) ?
                  p :
                  F(p);
          };
          
          var padNumber = function(/*uint*/n)
          // -------------------------------------
          {
              return n > 9999 ? ('' + n) : ('000'+n).substr(-3);
          };
          
          var fitVertical = function F(/*TextFrame*/tf, /*str='top'*/yRef, /*flo=.1*/Y_PRECISION)
          // -------------------------------------
          // Fits a textframe height to its content
          // i.e. adjusts the frame height to the optimal value w/o changing the width
          // <yRef> (opt.): reference pt, one of: 'top'(def.) | 'bottom' | 'center'
          // [REM] This routine supports rotated text frame
          {
              // Cache
              // ---
              F.Q || (F.Q={
              CS_INNER: +CoordinateSpaces.INNER_COORDINATES,
              RM_MULTIPLY: +ResizeMethods.MULTIPLYING_CURRENT_DIMENSIONS_BY,
              RM_ADDTO: +ResizeMethods.ADDING_CURRENT_DIMENSIONS_TO,
              AP_BOT: +AnchorPoint.BOTTOM_CENTER_ANCHOR,
              AP_TOP: +AnchorPoint.TOP_CENTER_ANCHOR,
              });
          
          
              // Default height multiplier. This value is only used if tf overflows in
              // its initial state. 1.5 is fine, usually.
              // ---
              var Y_FACTOR = 1.5;
          
              var ovf = tf.overflows,
                  dy;
          
              Y_PRECISION||(Y_PRECISION=.1);
          
              yRef = (yRef||'top').toUpperCase();
              'TOP' == yRef || 'BOTTOM' == yRef || yRef = '';
              yRef && (yRef+='_');
              yRef = +AnchorPoint[yRef + 'CENTER_ANCHOR'];
          
              // If tf originally overflows, we need to increase the height
              // ---
              while( tf.overflows )
                  tf.resize(F.Q.CS_INNER,yRef,F.Q.RM_MULTIPLY,[1,Y_FACTOR]);
          
              // Now, let's compute the maximal height variation (dy)
              // ---
              dy = tf.resolve(F.Q.AP_BOT, F.Q.CS_INNER)[0][1]-
                  tf.resolve(F.Q.AP_TOP, F.Q.CS_INNER)[0][1];
              if( ovf ) dy *= (1-1/Y_FACTOR);
          
              // Dichotomy on dy
              // ---
              while( dy > Y_PRECISION )
                  {
                  dy*=.5;
                  tf.resize(F.Q.CS_INNER,yRef,F.Q.RM_ADDTO, [0,dy*(tf.overflows?1:-1)]);
                  }
          
              // Last step, if needed
              // ---
              if( tf.overflows )
                  tf.resize(F.Q.CS_INNER,yRef,F.Q.RM_ADDTO,[0,dy]);
          };
          
          
          // =====================================
          // TASKS
          // =====================================
          
          var LABEL_TASKS = [
          // Array of label tasks (functions) in sync w/ label types
          // Each func takes a Graphic as 1st param, and may also
          // support a counter as 2nd param. It returns the label (string).
          // -------------------------------------
              function Custom_Format(g,n)
              {
                  return localize("%1_%2_%3"
                      , Custom_Format.prefix || ''
                      , (g=g.parentPage) ? g.name : 'NoParentPage'
                      , padNumber(n)
                      )
              },
              function Image_Name(g)      { return g.itemLink.name },
              function Image_File_Path(g) { return g.itemLink.filePath  },
              function XMP_Description(g) { return g.itemLink.linkXmp.description || "No description available." },
              function XMP_Author(g)      { return g.itemLink.linkXmp.author || "No author available." },
              function From_Clipboard(g)  { return From_Clipboard.data || "No clipboard data available." }
              ];
          
          var feedAvailableTaskNames = function(/*str[]&*/r,/*bool*/canClipboard,  a,re,t,i,s)
          // -------------------------------------
          {
              a = LABEL_TASKS;
              re = /_/g;
              t = canClipboard ? '' : 'From_Clipboard';
              for( i=a.length ; i-- ; t==(s=a[i].name) || (r[i]=s.replace(re,' ')) );
          };
          
          
          // =====================================
          // CONTEXT
          // =====================================
          
          var Context = function F()
          // -------------------------------------
          // Check the context and feed it as an object:
          // -> doc           Active document,
          // -> gxCount       Count of all graphics,
          // -> gxSelTargets  Array of selected graphics (or zero),
          // -> clipboard     Content of the clipboard, or zero,
          // -> labelOptions  Array of available label type options,
          // -> viewPrefs     Original document's view preferences,
          // -> error         Message of any occuring error.
          // Ret: 1 if all is fine, 0 otherwise.
          {
              // Is there any document?
              // ---
              if( !app.documents.length )
                  {
                  F.error = "Please open a document and try again.";
                  return 0;
                  }
              
              // Register the active document (if available).
              // ---
              if( !(F.doc = app.properties.activeDocument) )
                  {
                  F.error = "No active document available.";
                  return 0;
                  }
              
              // Save the total graphics count (nonzero required).
              // ---
              if( !(F.gxCount = F.doc.allGraphics.length) )
                  {
                  F.error = "The document contains no graphics.";
                  return 0;
                  }
              
              // Scan the selection.
              // ---
              F.gxSelTargets = getValidGraphics(app.selection);
          
              // Scan the clipboard.
              // ---
              F.clipboard = getClipboardText();
          
              // List the available label types (UI options.)
              // ---
              F.labelTypes = [];
              feedAvailableTaskNames(F.labelTypes, !!F.clipboard);
              
              // Backup the view prefs.
              // ---
              F.viewPrefs = F.doc.viewPreferences.properties;
              
              // All is fine.
              // ---
              return 1;
          };
          
          // =====================================
          // USER INTERFACE
          // =====================================
          
          var UserOptions = function F()
          // -------------------------------------
          // Run the UI and save the user options as an object:
          // -> minHeightPt   Minimum height of the label frame (in pts),
          // -> typeIndex     Selected label type,
          // -> offsetPt      Label offset (in pts),
          // -> targetSel     1::selection ; 0::all graphics
          // Ret: 1 (OK) or 0 (Cancel).
          {
              F.minHeightPt = 14.173;  // Could be managed through the dialog (?)
          
              const LAB_MIN_WIDTH = 100;
          
              var dlg = app.dialogs.add({ name: Context.gxSelTargets ? "Label Graphics" : "Label All Graphics" }),
                  ddTypes,      // Label type DropDown
                  meOffset,     // Label offset MeasurementEditbox
                  rgScope = 0,  // (opt.) RadiobuttonGroup (selection vs. allGraphics)
                  r;
          
              // Build the basic dialog.
              // ---
              with( dlg.dialogColumns.add() )
                  {
                  // Label types
                  // ---
                  with( dialogRows.add() )
                      {
                      dialogColumns.add().staticTexts.add({ staticLabel:"Label Type:", minWidth:LAB_MIN_WIDTH });
                      ddTypes = dialogColumns.add().dropdowns.add({ stringList:Context.labelTypes, selectedIndex:0 });
                      }
                  // Label Offset
                  // ---
                  with( dialogRows.add() )
                      {
                      dialogColumns.add().staticTexts.add({ staticLabel:"Label Offset:", minWidth:LAB_MIN_WIDTH });
                      meOffset = dialogColumns.add().measurementEditboxes.add({ editValue:0 });
                      }
                  }
              
              // Add an optional radio group to let the user choose:
              // (*) Selection   ( ) All graphics
              if( Context.gxSelTargets )
                  {
                  with( dlg.dialogColumns[0].dialogRows.add() )
                      {
                      dialogColumns.add().staticTexts.add({ staticLabel:"Run on:", minWidth:LAB_MIN_WIDTH });
                      with( rgScope = dialogColumns.add().radiobuttonGroups.add() )
                          {
                          radiobuttonControls.add({ staticLabel:"Selection", checkedState:true });
                          radiobuttonControls.add({ staticLabel:"All graphics", checkedState:false });
                          }
                      }
                  }
              else
                  {
                  dlg.dialogColumns[0].dialogRows.add().dialogColumns.add()
                      .staticTexts.add({ staticLabel:"***ALL GRAPHICS WILL BE PROCESSED***" });
                  }
          
              // Run the dialog and save the user options.
              // ---
              if( r = +dlg.show() )
                  {
                  F.typeIndex = ddTypes.selectedIndex;
                  F.offsetPt = meOffset.editValue;
                  F.targetSel = rgScope && (1 - rgScope.selectedButton);
                  }
              
              // Cleanup and return.
              // ---
              dlg.destroy();
              return r;
          };
          
          // =====================================
          // PROCESS
          // =====================================
          
          var Process = function F(  doc,a,t,f,i,s,o,gb)
          // -------------------------------------
          {
              const FO = +FitOptions.FRAME_TO_CONTENT;
          
              doc = Context.doc;
              
              // Get all valid graphics (targets) => a
              // ---
              a = (UserOptions.targetSel && Context.gxSelTargets) || getValidGraphics(doc.allGraphics);
              if( !a.length )
                  {
                  F.error = "No valid graphic object has been found.";
                  return 0;
                  }
          
              // Get/create the label layer.
              // ---
              F.layer = (t=doc.layers).itemByName(LAYER_PROPS.name);
              F.layer.isValid || (F.layer=t.add(LAYER_PROPS));
          
              // Get/create the label color.
              // ---
              F.color = (t=doc.colors).itemByName(COLOR_PROPS.name);
              F.color.isValid || (F.color=t.add(COLOR_PROPS));
              
              // Get/create the label paragraph style.
              // ---
              F.style = (t=doc.paragraphStyles).itemByName(STYLE_PROPS.name);
              F.style.isValid || (F.color=t.add(STYLE_PROPS));
          
              // Select and setup the right task.
              // ---
              t = UserOptions.typeIndex;
              f = LABEL_TASKS[t];
              while( 1 )
                  {
                  if( 'Custom_Format' == f.name )
                      {
                      // Set the prefix for the Custom_Format task,
                      // removing any non-digit character from doc.name
                      // ---
                      f.prefix = doc.properties.name.replace(/\D+/g,'');
                      break;
                      }
                  if( 'From_Clipboard' == f.name )
                      {
                      f.data = Context.clipboard;
                      }
                  break;
                  }
          
              // Switch to point units
              // ---
              doc.viewPreferences.properties = VIEW_PREFS_POINTS;
          
              // Loop
              // ---
              i = 0;
              o = FRAME_PROPS;
              while( t = a.pop() )
                  {
                  // Compute the label (string).
                  // ---
                  s = f(t,1+i);
                  
                  // Consider the parent frame bounds => gb
                  // and its parent spread.
                  // ---
                  gb = (t=t.parent).geometricBounds;
                  t = parentSpread(t);
                  if( !t ) continue;
          
                  // Create the label frame.
                  // ---
                  gb[0] = gb[2] + UserOptions.offsetPt;
                  gb[2] = gb[0] + UserOptions.minHeightPt;
                  o.geometricBounds = gb;
                  o.contents = s;
                  t = t.textFrames.add(F.layer, o);
                  t.parentStory.texts[0].appliedParagraphStyle = F.style;
          
                  fitVertical(t, 'top');
          
                  ++i;
                  }
          
              // Switch back to original units
              // ---
              doc.viewPreferences.properties = Context.viewPrefs;
          
              return 1;
          };
          
          // =====================================
          // ROOT
          // =====================================
          
          function LabelGraphics()
          {
              if( !Context() )
                  { alert( Context.error ); return; }
          
              if( !UserOptions() )
                  { return; }
          
              if( !Process() )
                  { alert( Process.error ); return; }
          
          };
          
          app.doScript(LabelGraphics,
              ScriptLanguage.javascript, undefined,
              UndoModes.entireScript, "LabelGraphics"
              );
          

           

          Not fully tested but should bring a starting point.

           

          @+

          Marc

          • 2. Re: Adding a function to
            sethkhouri Level 1

            Thank you.. Yes I should have given up days ago...

             

            Thank you again for your help.

            • 3. Re: Adding a function to
              sethkhouri Level 1

              Hi Marc,

               

              thank you for your help with this.

              Just a question. If I only wanted to include say JPG, TIFF & PSD how do I do this?

              i was looking at .imageTypeName == "ext" but i just can't get that to work..

              • 4. Re: Adding a function to
                Peter Kahrel Adobe Community Professional & MVP

                Mmmm -- dlg = app.dialogs.add(), eh?

                • 5. Re: Adding a function to
                  sethkhouri Level 1

                  Hi

                   

                  thanks for getting back to me, sorry am kind of very new to scripting, where do I add this?

                  currently the script labels allGraphics, But I want to only label images like jpg, tiff, psd etc, basically all images no vector pdf etc.

                   

                  thank you

                  • 6. Re: Adding a function to
                    Marc Autret Level 4

                    Hi,

                     

                    Link objects have a linkType property that returns a string ("TIFF", "JPEG", "Photoshop"…) depending on the link type. So you could filter item links this way:

                     

                    1. At the beginning of the script, add a constant that defines the allowed types:

                     

                    const LINK_TYPES = { 
                        JPEG:          1,
                        TIFF:          1,
                        Photoshop:     1,
                        };
                    
                    
                    

                     

                    2. Then, in the getValidGraphics function, refine the item link test accordingly. Replace

                     

                    if( 'itemLink' in t && t.parent instanceof Rectangle )
                        {
                        r.push(t);
                        }
                    

                     

                    by

                     

                    if( 'itemLink' in t && (t.parent instanceof Rectangle) && LINK_TYPES[t.itemLink.linkType] )
                        {
                        r.push(t);
                        }
                    
                    

                     

                    That should work.

                     

                    @+

                    Marc

                    • 7. Re: Adding a function to
                      sethkhouri Level 1

                      Ahh

                       

                      thank you, I am really starting to get into this. I just wish i didn't have a day job that prevented me from playing more.

                      • 8. Re: Adding a function to
                        sethkhouri Level 1

                        one last question.. and again thank you so much for your help

                        but the custom function where it added the file name + the page name + the image number, counts the numbers on the spread, is it possible to do this for a page? so after it labels all the images on page 1 starting form 001 to what ever it then goes over to the second page on the spread and starts the loop again.

                        for example you may have a spread with one 2 images on it 1 image on each page, the label would add filename_page number_001 to each image

                        so you would end up with 2 labels with the almost the same code except the page number being the difference?

                         

                        does that make sense?

                        • 9. Re: Adding a function to
                          sethkhouri Level 1

                          Is this to do with the parentSpread? the script seems to go over the spread and *** the counter and not the page.

                          not sure where I should be looking,

                           

                          thank you