12 Replies Latest reply on Dec 5, 2016 3:54 PM by spaciousmind

    need a little help with an export script

    spaciousmind Level 1

      Hey guys, I've been using basic scripts to export single documents in illustrator for some time now,
      I wanted to make a script that would loop through all open documents and save them all out as pdf's
      I looked through one of the adobe sample scripts to use as a base, ......

       

      After much trial and error, I've pretty much got it working how I want EXCEPT it only seems to loop through around half of my open documents.

      If I have 5 or 6 open, it only does 3, if I have 3 or 4 it only does 2 and so on.
      theres no error message, it gives me the "Documents saved as PDF" line but always leaves a few behind.

       

      what I want is for it to loop through all open docs, saving each one out as pdf and closing each document as it goes.
      (so when it finishes I should have no open documents)


      I imagine it's something quite simple but can't figure it out for the life of me.

      Can anyone help me out with this? maybe explain where it's going wrong?

       

      try {
          if (app.documents.length > 0 ) {
                  pdfSaveOpts = getPDFOptions( );
                  for ( i = 0; i < app.documents.length; i++ ) {
                      sourceDoc = app.documents[i]; // returns the document object
                      //=============Find Current Documents path================//
                      var CurrentPath = sourceDoc.path;
                      //=============Establish current documents destination===============//
                      var folderPDF = Folder(CurrentPath + '/' + 'new PDFs');
                      //=============Check if it exist, if not create it.============//
                      if(!folderPDF.exists) folderPDF.create();                                        
                      // Get the file to save the document as pdf into
                      targetFile = this.getTargetFile(sourceDoc.name, '.pdf', folderPDF);
                              if (folderPDF) {                                
                                      // Save as pdf
                                      sourceDoc.saveAs( targetFile, pdfSaveOpts );
                                      sourceDoc.close();
                                      }
                  }
                  alert( 'Documents saved as PDF' );
          }
          else{
              throw new Error('There are no document open!');
          }
      }
      catch(e) {
          alert( e.message, "Script Alert", true);
      }
      
      //**************************/
      
      function getTargetFile(docName, ext, destFolder) {
          var newName = "";
      
          // if name has no dot (and hence no extension),
          // just append the extension
          if (docName.indexOf('.') < 0) {
              newName = docName + "_HR" + ext;
          } else {
              var dot = docName.lastIndexOf('.');
              newName += docName.substring(0, dot);
              newName += "_HR"
              newName += ext;
          }
          
          // Create the file object to save to
          var myFile = new File( destFolder + '/' + newName );
          
          // Preflight access rights
          if (myFile.open("w")) {
              myFile.close();
          }
          else {
              throw new Error('Access is denied');
          }
          return myFile;
      }
      
      //***************************/
      
      
      function getPDFOptions()
      {
          // Create the PDFSaveOptions object to set the PDF options
          var pdfSaveOpts = new PDFSaveOptions();
          
          // Setting PDFSaveOptions properties. Please see the JavaScript Reference
          // for a description of these properties.
          // Add more properties here if you like
          pdfSaveOpts.pDFPreset = "[Illustrator Default]";
          
          
          // uncomment to view the pdfs after conversion.
          // pdfSaveOpts.viewAfterSaving = true;
          
      
          return pdfSaveOpts;
      }
      
      
      


      thanks!

        • 1. Re: need a little help with an export script
          Silly-V Adobe Community Professional

          Not sure what's happening here, but to get your File object to write to, there's no need to create a file with the write command, simply returning the File object will do. Does your access really get denied?

          1 person found this helpful
          • 2. Re: need a little help with an export script
            spaciousmind Level 1

            Oh, thanks for responding Silly-V, could you please clarify how I might remove that unecessary step?

             

            Are you referring to the myFile = newFile line in the getTargetFile Function?
            I don't fully understand what's going on there, If I try to remove that line it tells me myFile is undefined, if I try and remove all the myFile stuff it says illegal argument

            And no, my access has never been denied, that was just a hangover from the adobe sample script I used as a starting point (SaveDocsAsPDF.jsx) wasn't sure what it did so left it in there just incase.

            • 3. Re: need a little help with an export script
              williamadowling Level 4

              lines 50-56:

               

              // Preflight access rights  
              if (myFile.open("w")) {  
                      myFile.close(); 
                  } 
              else {  
              throw new Error('Access is denied');  
                  } 
              
              

              Silly-V is saying that since you've already created the file object in line 47, then you don't need the rest. I don't believe that that block would work as expected if you didn't have the correct permissions. If you can't open/read/write a file, you'll get an error by default.

               

              You should easily be able to get away with deleting lines 50-56 so your getTargetFile function looked like this:

               

              function getTargetFile(docName, ext, destFolder) { 
                  var newName = "";  
              // if name has no dot (and hence no extension),  
              // just append the extension  
              if (docName.indexOf('.') < 0) {  
                      newName = docName + "_HR" + ext;  
                  } else {  
                      var dot = docName.lastIndexOf('.');  
                      newName += docName.substring(0, dot);  
                      newName += "_HR"  
                      newName += ext; 
                  } 
              // Create the file object to save to  
                  var myFile = new File( destFolder + '/' + newName );  
              return myFile;  
              } 
              
              
              1 person found this helpful
              • 4. Re: need a little help with an export script
                Larry G. Schneider Adobe Community Professional & MVP

                Try changing this line for ( i = 0; i < app.documents.length; i++ ) to for (  i < app.documents.length-1; i => 0; i-- )

                When changing the length of an array, you need to process it backwards.

                1 person found this helpful
                • 5. Re: need a little help with an export script
                  spaciousmind Level 1

                  I tried changing those around but when I try to run it the editor just highlights the > and tells me it does not have a value.

                   

                  I fumbled around with variations on that theme and found that changing it to for (  i < app.documents.length-1; i = 1; i-- ){
                  works a little better than the original line, it gets through 5 out of 6 documents correctly but then always leaves the last one behind and throws up a "no such element" error at the end.

                   

                  The solutions gotta be in that line. I just don't know how to get that i => 0 in there in a way that works?

                  • 6. Re: need a little help with an export script
                    Silly-V Adobe Community Professional

                    Change it to

                    for (  i < app.documents.length-1; i > -1; i-- ){

                    • 7. Re: need a little help with an export script
                      spaciousmind Level 1

                      with this line the script runs and comes up with "documents saved as PDF" message, but unfortunately does nothing.

                      • 8. Re: need a little help with an export script
                        williamadowling Level 4

                        shouldn't it be:

                         

                        for ( i = app.documents.length-1; i>-1; i--)

                         

                        you have to set the loop variable to be equal to something in the first part. i think that's why he's getting "< does not have a value"

                        • 9. Re: need a little help with an export script
                          spaciousmind Level 1

                          That's it!!!

                           

                          Many thanks, this is going to come in handy

                          • 10. Re: need a little help with an export script
                            Larry G. Schneider Adobe Community Professional & MVP

                            Thanks for the correction.

                            • 11. Re: need a little help with an export script
                              williamadowling Level 4

                              You should consider changing the alert that says "Documents saved as PDF" because it's not actually confirming whether the documents were sucessfully saved. It's merely saying that you've reached the end of the loop without a runtime error.

                               

                              When you were getting that message without anything being saved, it was because your loop was never actually executing, and it was failing to execute silently. The initial loop conditions were false, so nothing was executed.

                               

                              Consider something like this:

                               

                              try {  
                                  var savedDocs = 0;
                                  var openDocs = app.documents.length;
                                  if (app.documents.length > 0 ) {  
                                      pdfSaveOpts = getPDFOptions( );  
                                      for ( i = app.documents.length-1; i > -1 ; i-- ){
                                          sourceDoc = app.documents[i]; // returns the document object  
                                          //=============Find Current Documents path================//  
                                          var CurrentPath = sourceDoc.path;  
                                          //=============Establish current documents destination===============//  
                                          var folderPDF = Folder(CurrentPath + '/' + 'new PDFs');  
                                          //=============Check if it exist, if not create it.============//  
                                          if(!folderPDF.exists) folderPDF.create();                                          
                                          // Get the file to save the document as pdf into  
                                          targetFile = this.getTargetFile(sourceDoc.name, '.pdf', folderPDF);  
                                          if (folderPDF) {                                  
                                              // Save as pdf  
                                              sourceDoc.saveAs( targetFile, pdfSaveOpts );  
                                              sourceDoc.close();  
                                              savedDocs++;
                                          }  
                                      }
                              
                                      if(savedDocs == openDocs)
                                      {
                                          alert( 'Documents saved as PDF' );  
                                      }
                                      else
                                      {
                                          var difference = openDocs - savedDocs;
                                          alert(difference + " documents did not save properly")
                                      }
                                  }  
                                  else{  
                                      throw new Error('There are no document open!');  
                                  }  
                              }  
                              catch(e) {  
                                  alert( e.message, "Script Alert", true);  
                              }  
                              

                               

                              This is by no means a perfect check but it's a step closer.

                              1 person found this helpful
                              • 12. Re: need a little help with an export script
                                spaciousmind Level 1

                                Thanks again It seems to work well - that check should be plenty sufficient for me - I can't imagine I'll encounter the error very often but it's really good to have it in there.
                                I edited it slightly so that it tells me how many documents it saved out too, a small thing but helpful to know when dealing with many files at once.