15 Replies Latest reply on Feb 9, 2017 6:29 AM by OndrejL

    Script to reorder pages?

    shiramozes

      I'm looking for a script to reorder the pages in a large document (a few hundred pages).

       

      I need to be able to create the new order based on the old page numbers [for example: I need to specify that the new order should be 100, 212, 3, 9, 178.... all referencing the original page numbers.] When I move pages manually the old page numbers are no longer valid, which is why I can't do it manually.

       

      Anyone that's seen/written such a script is invited to reply, as well as anyone who'd be willing to try writing one.  Thanks.

        • 1. Re: Script to reorder pages?
          [Jongware] Most Valuable Participant

          Hey, that was far more hard than I thought!

           

          This script appears to be working -- but, admittedly, I only tested it with a 20-page document and some random reiterations. Run on a copy of your document, and holler if it ain't right. (And, boyo, do I hope it works ...)

           

          You can fill in your new order in the first line, comma separated. You can also enter a range, like "5-10", if you happen to have a few pages in the original order. All numbers should be entered inbetween the quotes on one single line.

           

          var order="1,20,2,19,3,18,4,17,5,16,6,15,7,14,8,13,9,12,10,11";
          // Create an array out of the list:
          ranges = toSeparate (order);
          if (ranges.length != app.activeDocument.pages.length)
          {
           alert ("Page number mismatch -- "+ranges.length+" given, "+app.activeDocument.pages.length+" in document");
           exit(0);
          }
          // Consistency check:
          sorted = ranges.slice().sort(numericSort);
          for (a=0; a<sorted.length-1; a++)
          {
           if (sorted[a] < sorted[a+1]-1 ||
            sorted[a] == sorted[a+1])
            alert ("Mismatch from "+sorted[a]+" to "+sorted[a+1]);
          }
          // alert ("New order for "+order+"\nis "+ranges.join(", "));
          // Convert from 1..x to 0..x-1:
          for (moveThis=0; moveThis<ranges.length; moveThis++)
           ranges[moveThis]--;
          for (moveThis=0; moveThis<ranges.length; moveThis++)
          {
           if (moveThis != ranges[moveThis])
           {
            try{
             app.activeDocument.pages[ranges[moveThis]].move (LocationOptions.BEFORE, app.activeDocument.pages[moveThis]);
            } catch(_) { alert ("problem with page "+moveThis+"/index "+ranges[moveThis]); }
           }
           for (updateRest=moveThis+1; updateRest<ranges.length; updateRest++)
            if (ranges[updateRest] < ranges[moveThis])
             ranges[updateRest]++;
          }
          function toSeparate (list)
          {
           s = list.split(",");
           for (l=0; l<s.length; l++)
           {
            try {
            if (s[l].indexOf("-") > -1)
            {
             indexes = s[l].split("-");
             from = Number(indexes[0]);
             to = Number(indexes[indexes.length-1]);
             if (from >= to)
             {
              alert ("Cannot create a range from "+from+" to "+to+"!");
              exit(0);
             }
             s[l] = from;
             while (from < to)
              s.splice (++l,0,++from);
            }} catch(_){}
           }
          // s.sort (numericSort);
           return s;
          }
          function numericSort(a,b)
          {
           return Number(a) - Number(b);
          }
          

          Copy and paste into a plain text editor -- the ESTK Editor that comes with InDesign is okay -- and save as "rearrangePages.jsx" into your scripting folder. It should immediately become available in your Scripts panel. Then just double-click to run.

           

          It should warn you of duplicate numbers and some other mismatches I could think of. If it shows an error ("cannot create range"), your input is wrong. If it alerts you while running ("problem with page ...") it cannot move that page for some reason...

           

          Absolutely No Guarantees. Run On A Copy Only. It May Seriously Damage Your Document If It Goes Wrong.

          • 2. Re: Script to reorder pages?
            Marc Autret Level 4

            Great job, Jong !

             

            I see another approach using Page.id :

             

             

            var order = "20, 1-4, 19, 18, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10-11";
            reorderPages(order);
            
            
            function reorderPages(/*str*/newOrder)
            //--------------------------------------
            {
            var pages = app.activeDocument.pages;
            
            var pgMap = (function()
                 {
                 var items = newOrder.replace(/[^\d,-]/g,'').split(',');
                 var r = [], bkp={}, i, sz, p;
                 
                 while(i=items.shift())
                      {
                      i = i.split('-');
            
                      // don't allow "x-y-z"
                      if ( (sz=i.length) > 2 ) return false;
            
                      // don't allow "max-min"
                      if ( i[0] > i[sz-1] ) return false;
            
                      for( p=+i[0] ; p<= +i[sz-1] ; p++ )
                           {
                           if (!pages.item(''+p).isValid) return false;
                           
                           if (''+p in bkp) return false;
                           bkp[''+p]=1;
            
                           r.push(pages.item(''+p).id);
                           }
                      }
                 return r;
                 })();
                 
            if ( !pgMap )
                 {
                 alert("Invalid reordering string");
                 return false;
                 }
            
            var sz = pgMap.length;
            if (sz != pages.length)
                 {
                 alert ("Page number mismatch -- "+pgMap.length+" given, "+pages.length+" in document");
                 return false;
                 }
            
            // at this point, {pgMap} contains a valid permutation
            
            var i;
            app.scriptPreferences.enableRedraw = false;
            for( i=0 ; i < sz ; i++ )
                 pages.itemByID(pgMap[i]).move(LocationOptions.BEFORE, pages[i]);
            app.scriptPreferences.enableRedraw = true;
            }
            

             

            Does it work?

             

            @+

            Marc

            • 3. Re: Script to reorder pages?
              Harbs. Level 6

              Here's yet another approach: (This is a script I wrote quite a long time ago, so please excuse the style)

               

              if (app.documents.length == 0){exit()}
              
              reRun = movePages();
              while (reRun){reRun = movePages()}
              
              function movePages(){
              var doc = app.activeDocument;
              var origPN =[];
              for (var i=0;i<doc.pages.length;i++){
              //     var myPN = doc.pages[i].extractLabel("pageNumber");
                   if (doc.pages[i].extractLabel("pageNumber") == ""){
                        doc.pages[i].insertLabel("pageNumber",doc.pages[i].name);
                        }
                   origPN.push(doc.pages[i].extractLabel("pageNumber"));
                   }
              var myDialog = app.dialogs.add({name:"Move Pages",canCancel:true});
              with(myDialog){
                with(dialogColumns.add()){
                  with(borderPanels.add()){
                    with(dialogColumns.add()){
                      staticTexts.add({staticLabel:"Old Page Number:"});
                      staticTexts.add({staticLabel:"New Page Number:"});
                      staticTexts.add({staticLabel:"Rerun Script on OK:"});
                      }
                    with(dialogColumns.add()){
                      var oldPNDD = dropdowns.add( {stringList: origPN, selectedIndex: 0} );
                      var newPNField = textEditboxes.add({});
                      var reRunCB = checkboxControls.add({checkedState:true})
                      }
                    }
                  }
                }
              var myResult = myDialog.show();
              if(myResult == true){
                var oldPN = oldPNDD.selectedIndex; 
                var newPN = newPNField.editContents;
                var reRun = reRunCB.checkedState;
                myDialog.destroy();
                }else{myDialog.destroy();exit()}
              myReplPage = findPage(newPN,doc);
              if (myReplPage == null){alert ("Invalid Page");exit()}
              myOrigPage = findOrigPage(origPN[oldPN],doc);
              if (myOrigPage.documentOffset > myReplPage.documentOffset){
                myOrigPage.move(LocationOptions.before,myReplPage);
                }else{
                myOrigPage.move(LocationOptions.after,myReplPage);
                }
              return reRun
              }
              function findPage(myPage,doc){
                for (var i=0;i<doc.pages.length;i++){
                  if (doc.pages[i].name == myPage){
                    return doc.pages[i];
                    }
                  }
                return null;
                }
              
              function findOrigPage(myPage,doc){
                for (var i=0;i<doc.pages.length;i++){
                  if (doc.pages[i].extractLabel("pageNumber") == myPage){
                    return doc.pages[i]
                    }
                  }
                }
              

               

              It went along with this accompanying script to clear out the saved page positions:

               

              if (app.documents.length == 0){exit()}
              var doc = app.activeDocument;
              for (var i=0;i<doc.pages.length;i++){
                   doc.pages[i].insertLabel("pageNumber","");
                   }
              
              • 4. Re: Script to reorder pages?
                shiramozes Level 1

                Sorry for the delay in responding.

                 

                This works just great!  I tested it on a 53-page file and on a 282-page file.

                When I had my "new order" down pat it ran well.

                 

                It told me if I was missing pages in the new order, which was good.

                As far as error messages, I got "problem with page..." on a 300-page file, but I realized then that was because it was a file with facing pages.

                At one point, I received another error (a mismatch error if I recall correctly) but it did continue running. Could it be that I had a duplicate there?

                 

                I don't know the first thing about scripting. Your instructions were very clear and it did the job.  Thanks so much!!

                • 5. Re: Script to reorder pages?
                  shiramozes Level 1

                  I tried running this script, to see if it will run faster/better than the one Jong sent me, but I couldn't get it to work.  Like I said, I don't know the first thing about scripting, so I probably put the list of the "new order" in the wrong place. Where was it supposed to go?

                  • 6. Re: Script to reorder pages?
                    Marc Autret Level 4

                    shiramozes wrote:

                     

                    I tried running this script, to see if it will run faster/better than the one Jong sent me, but I couldn't get it to work.  Like I said, I don't know the first thing about scripting, so I probably put the list of the "new order" in the wrong place. Where was it supposed to go?

                    At the very beginning:

                    var order = "20, 1-4, 19, 18, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10-11";

                     


                    What error message did you get?

                     

                    (Note that because the script checks that the pages referred to actually exist, it uses a property --isValid-- which is available only in ID CS4.)

                    • 7. Re: Script to reorder pages?
                      shiramozes Level 1

                      I got Error 23  does not have a value on Line 25. I tried it on two files and got the same error.

                      I am using ID CS4.

                      • 8. Re: Script to reorder pages?
                        [Jongware] Most Valuable Participant
                        At one point, I received another error (a mismatch error if I recall correctly) but it did continue running. Could it be that I had a duplicate there?

                         

                        Ah, I see I forgot to stop the script on this particular error ... It happens when you have a duplicate or non-consecutive page numbers in the "order" string. I'm surprised it kept on running anyway Best to stop the script, just in case it happens again. After this line

                         

                        alert ("Mismatch from "+sorted[a]+" to "+sorted[a+1]);

                         

                        simply add a new line

                         

                        exit(0);

                         

                        before the closing brace. It does what it says: exit the script (in this case, back to the InDesign UI).

                        • 9. Re: Script to reorder pages?
                          Marc Autret Level 4

                          shiramozes wrote:

                           

                          I got Error 23  does not have a value on Line 25. I tried it on two files and got the same error.

                          I am using ID CS4.

                           

                          Hi shiramozes,

                           

                          I can't explain the reason of this error -- sorry

                           

                          I tried my script on a 220-page document with this reordering string:

                          var order = "20, 1-4, 101-150, 19, 18, 17, 21-100, 5, 16, 6, 15, 201-220,7, 14, 8, 13, 151-200,9, 12, 10-11";

                           

                          The script made the job in less than 8 seconds.

                           

                          Could you show me the order you've used?

                           

                          @+

                          Marc

                          • 10. Re: Script to reorder pages?
                            shiramozes Level 1

                            Here's the script with my order:

                             

                            var order = "191,192,165,76,169,167,19,61,250,201,143,2,3,4,5,6,7,8,9,10,190,51,95,125,11,12,249,13,5 2,70,122,14,15,16,17,18,60,68,123,252,262,20,1,22,23,121,128,126,24,25,178,28,176,179,29,3 0,27,31,168,181,127,32,33,170,183,36,37,38,39,182,164,133,159,98,172,59,56,40,41,261,42,43 ,180,161,53,35,34,220,26,186,21,77,226,44,264,266,45,171,136,132,46,47,48,49,50,244,129,25 1,54,166,195,62,63,64,265,268,65,66,67,196,69,204,145,146,147,71,72,73,74,124,75,118,58,55 ,269,270,57,148,130,149,150,151,131,119,257,120,229,97,243,152,153,154,155,156,135,157,158 ,140,99,160,162,173,174,134,96,194,107,100,101,102,103,104,105,106,108,109,141,111,112,113 ,175,177,247,184,185,114,115,116,117,138,94,78,110,79,80,137,81,82,83,84,85,86,87,88,89,90 ,91,92,188,189,193,187,199,200,142,263,260,202,203,239,205,198,144,206,207,208,209,210,211 ,212,139,197,213,214,215,216,217,218,163,219,221,222,223,224,225,227,228,230,231,232,233,2 34,235,236,237,238,246,240,242,245,248,253,254,255,256,258,259,267,93,241"; reorderPages(order);

                             


                            function reorderPages(/*str*/newOrder)
                            //--------------------------------------
                            {
                            var pages = app.activeDocument.pages;

                             

                            var pgMap = (function()
                                {
                                var items = newOrder.replace(/[^\d,-]/g,'').split(',');
                                var r = [], bkp={}, i, sz, p;
                               
                                while(i=items.shift())
                                      {
                                      i = i.split('-');

                             

                                      // don't allow "x-y-z"
                                      if ( (sz=i.length) > 2 ) return false;

                             

                                      // don't allow "max-min"
                                      if ( i[0] > i[sz-1] ) return false;

                             

                                      for( p=+i[0] ; p<= +i[sz-1] ; p++ )
                                        & nbsp; {
                                        & nbsp; if (!pages.item(''+p).isValid) return false;
                                        & nbsp;
                                        & nbsp; if (''+p in bkp) return false;
                                        & nbsp; bkp[''+p]=1;

                             

                                        & nbsp; r.push(pages.item(''+p).id);
                                        & nbsp; }
                                      }
                                return r;
                                })();
                               
                            if ( !pgMap )
                                {
                                alert("Invalid reordering string");
                                return false;
                                }

                             

                            var sz = pgMap.length;
                            if (sz != pages.length)
                                {
                                alert ("Page number mismatch -- "+pgMap.length+" given, "+pages.length+" in document");
                                return false;
                                }

                             

                            // at this point, {pgMap} contains a valid permutation

                             

                            var i, pg;
                            app.scriptPreferences.enableRedraw = false; for( i=0 ; i < sz ; i++ )
                                pages.itemByID(pgMap[i]).move(LocationOptions.BEF ORE, pages[i]); app.scriptPreferences.enableRedraw = true; }

                            • 11. Re: Script to reorder pages?
                              Marc Autret Level 4

                              A lot of & nbsp; entities seem to parasitize the code -- I don't know where they're coming from.

                               

                              Use rather the script I've zipped and attached to my previous post.

                               

                              @+

                              Marc

                              • 12. Re: Script to reorder pages?
                                shiramozes Level 1

                                I couldn't open the zip file - but I did recopy the original script and it works!!

                                 

                                It took about the same time to run as the script that I got from Jong. Are there any differences between the way the two scripts run?

                                • 13. Re: Script to reorder pages?
                                  [Jongware] Most Valuable Participant

                                  There are substantial differences in applied logic!

                                   

                                  • I think Harbs' script marks each page with a unique id, so after shuffling he still can find the "original" (unshuffled) page number (right?)
                                  • Marc's way is going over the shuffled pages and storing a reference to each one in a stack (the 'push' stuff). Then he goes over this stack, 'popping' off the pages in the correct order. Very cunning.
                                  • I went for the "why" -- why do you get confused when you have to shuffle the pages? Because some of the page numbers get out of whack; others stay unchanged. Why? Took me a bit of experimenting to get it right.

                                   

                                  I think all scripts run in the same time because all the sorting, pushing, labeling, and looping doesn't really take much time. It's when the script actually has to move pages around that it slows down (the amount of internal data to consider is .. considerable). Since each script ultimately has to deliver the document in the same shuffled order (did you actually check? ) and we are all smart enough to only move each page once, all 3 scripts take just about as long.

                                  • 14. Re: Script to reorder pages?
                                    OndrejL

                                    Hi,

                                     

                                    I got this error:

                                    TypeError: app.activeDocument is undefined

                                     

                                    Anybody some idea how to fix it

                                    • 15. Re: Script to reorder pages?
                                      OndrejL Level 1

                                      I am sorry, it is InDesign,

                                       

                                      i need it for acrobat