8 Replies Latest reply on Aug 13, 2009 9:30 AM by FivePicaPica

    Export by Paragraph Style to text file

    FivePicaPica Level 4

      I have an InDesign document (several really), where I'd like to extract all text formatted with a certain paragraph style to create a glossary.

       

      I looked at ExportAllStories and Dave Saunder's ChangeCaseofSelectedStyle to try and cobble something together (my scripting skills are next to zero). I got this far, now I'm stuck and getting errors.

       

      Any help?

       

       

       

      if ((app.documents.length != 0) && (app.selection.length != 0)) {
          myDoc = app.activeDocument;
          myStyles = myDoc.paragraphStyles;
          myStringList = myStyles.everyItem().name;
          myExportFormatList = ["Text Only","RTF", "InDesign Tagged Text"];

       

          var myDialog = app.dialogs.add({name:"ExtractParagraphByStyle"})
          with(myDialog){
              with(dialogColumns.add()){
                  with (dialogRows.add()) {
                      with (dialogColumns.add()) {
                          staticTexts.add({staticLabel:"Paragraph Style:"});
                      }
                      with (dialogColumns.add()) {
                          myStyle = dropdowns.add({stringList:myStringList,selectedIndex:0,minWidth:133});
                      }
                  }
                  with (dialogRows.add()) {
                      with (dialogColumns.add()) {
                          staticTexts.add({staticLabel:"Export as:"});
                      }
                      with(myExportFormatButtons = radiobuttonGroups.add()){
                          radiobuttonControls.add({staticLabel:"Text Only", checkedState:true});
                          radiobuttonControls.add({staticLabel:"RTF"});
                          radiobuttonControls.add({staticLabel:"InDesign Tagged Text"});
                      }
                  }
              }
          }      

       


      myReturn = myDialog.show();
              if (myReturn == true){
                  //Get the values from the dialog box.
                  myExportFormat = myExportFormatButtons.selectedButton;
                  myDialog.destroy;
                  myFolder= Folder.selectDialog ("Choose a Folder");
                  if((myFolder != null)&&(app.activeDocument.stories.length !=0)){
                      myExtractParagraphByStyle(myExportFormat, myFolder);
                  }
              }
              else{
                  myDialog.destroy();s
              }
          }

       

      //myExportStories function takes care of exporting the stories.
      //myExportFormat is a number from 0-2, where 0 = text only, 1 = rtf, and 3 = tagged text.
      //myFolder is a reference to the folder in which you want to save your files.
      function myExtractParagraphByStyle(myExportFormat, myFolder){
          for(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){
              myStory = app.activeDocument.stories.item(myCounter);
              myID = myStory.id;
              switch(myExportFormat){
                  case 0:
                      myFormat = ExportFormat.textType;
                      myExtension = ".txt"
                      break;
                  case 1:
                      myFormat = ExportFormat.RTF;
                      myExtension = ".rtf"
                      break;
                  case 2:
                      myFormat = ExportFormat.taggedText;
                      myExtension = ".txt"
                      break;
              }
              myFileName = "StoryID" + myID + myExtension;
              myFilePath = myFolder + "/" + myFileName;
              myFile = new File(myFilePath);
              myStory.exportFile(myFormat, myFile);
          }
      }
      // +++++++ Functions Start Here +++++++++++++++++++++++

       

      function errorExit(message) {
          if (arguments.length > 0) {
              if (app.version != 3) { beep() } // CS2 includes beep() function.
              alert(message);
          }
          exit(); // CS exits with a beep; CS2 exits silently.
      }

        • 1. Re: Export by Paragraph Style to text file
          Thomas B. Nielsen Level 3

          Hi FivePicaPica,

           

          You have not mentioned what version of Indesign this should work on - the below example is CS3 (Searching has changed from CS2 > CS3)


          I think you are complicating things, if you do a search  in your document for all text formatted with the desired style, you should end up with an array of text objects. You can then export this text as you want.

           

          A simple example illustrating the idea:

           

          app.findTextPreferences = NothingEnum.nothing;
          app.changeTextPreferences = NothingEnum.nothing;

           

          //Set the find options.
          app.findChangeTextOptions.caseSensitive = false;
          app.findChangeTextOptions.includeFootnotes = false;
          app.findChangeTextOptions.includeHiddenLayers = false;
          app.findChangeTextOptions.includeLockedLayersForFind = false;
          app.findChangeTextOptions.includeLockedStoriesForFind = false;
          app.findChangeTextOptions.includeMasterPages = false;
          app.findChangeTextOptions.wholeWord = false;

           

          //Search the document for the string "Text".
          app.findTextPreferences.findWhat = "";

           

          app.findTextPreferences.appliedParagraphStyle = "Rød";

           

          var myFoundItems = app.documents.item(0).findText();

           

          app.findTextPreferences = NothingEnum.nothing;
          app.changeTextPreferences = NothingEnum.nothing;

           

          alert("Found " + myFoundItems.length + " instances of the search string.");

           

          for (i = 0; i < myFoundItems.length; i++) {
              //myFoundItems[i].exportFile(); // or combine before exporting?
              // You might have to check the type of myFoundItems[i] before exporting, or atleast use a try / catch
          }

           

          Message was edited by: Thomas B. Nielsen

          1 person found this helpful
          • 2. Re: Export by Paragraph Style to text file
            FivePicaPica Level 4

            Hi Thomas,

             

            for (i = 0; i < myFoundItems.length; i++) {
                //myFoundItems[i].exportFile(); // or combine before exporting?
                // You might have to check the type of myFoundItems[i] before exporting, or atleast use a try / catch
            }

             

            Thanks. I think what you wrote is along the right lines, but I'm stuck at this part. I would want to combine the files into a single text file. Not sure how to do that. All this code is shiny and new to me.

             

            I'm using CS4 .

             

            I know I'm over complicating it with the drop boxes, etc, but we'd use this alot for endnotes, glossaries... If I can get yours to work, I think I could figure out the rest in my free time. Having the dropdown box helps, because I won't have to edit the code everytime a co-worker wants to use it. I think I've got the first part working, but I'm a bit lost on the rest. (I won't post my slightly updated code; I don't want to confuse matters further...)

            • 3. Re: Export by Paragraph Style to text file
              [Jongware] Most Valuable Participant

              If you only need the plain text, unformatted, it's easiest to create a new file and write the strings one by one onto it -- file.write (found[i]). Since you are copying entire paragraphs, you automatically get the ending return with it (if not, you could use file.writeln).

              If you want some of the formatting left, you're going to get all of it.

               

              Copy each of the found paragraphs into a new text frame; then export just this text frame, and delete it when done:

               

              someTextFrame = app.activeDocument.textFrames.add (undefined, LocationOptions.AT_BEGINNING, app.activeDocument.pages[0]);
              someTextFrame.geometricBounds = ["10mm","10mm","200mm","200mm"];
              
              // searching comes here ..
              
              for (i=0; i<myFoundItems.length; i++)
                myFoundItems[i].duplicate (LocationOptions.AT_END, someTextFrame.texts[0]);
              

               

              oughta work. It creates a new frame on the first page and copies all found texts into it. Then you can do

               

              someTextFrame.exportFile (...);

               

              and finish off with

               

              someTextFrame.remove();
              1 person found this helpful
              • 4. Re: Export by Paragraph Style to text file
                FivePicaPica Level 4

                Thanks! It's not working perfectly but well enough and I do want the formatting. Phew.

                 

                I used this to export.

                 

                someTextFrame.exportFile (ExportFormat.textType, File("/Users/robot/Desktop/TestDocument.inx"));

                 

                It says I'm trying to export an unsupported format...

                 

                I'm doing this on the fly. Can you recommend any good on your desk beginner books for learning this stuff? (Perhaps similar to O'Reilly's GREP PDF )

                • 5. Re: Export by Paragraph Style to text file
                  Thomas B. Nielsen Level 3

                  The example script, export all text to file might give you some clues:

                   

                  //ExportAllText.jsx
                  //An InDesign CS4 JavaScript
                  //
                  //Exports all of the text in the active document as a single
                  //text file. To do this, the script will create a new document,
                  //combine the stories in the new document using export/import,
                  //and then export the text from the new document.
                  main();
                  function main(){
                      mySetup();
                      mySnippet();
                      myTeardown();
                  }
                  function mySetup(){
                      var myDocument = app.documents.add();
                      myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
                      myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
                      myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
                      var myPage = myDocument.pages.item(0);
                      var myTextFrameA = myPage.textFrames.add();
                      myTextFrameA.geometricBounds = [72, 72, 144, 288];
                      myTextFrameA.contents = "This is story 1.";
                      var myTextFrameB = myPage.textFrames.add();
                      myTextFrameB.geometricBounds = [228, 72, 300, 288];
                      myTextFrameB.contents = "This is story 2.";
                      var myTextFrameC = myPage.textFrames.add();
                      myTextFrameC.geometricBounds = [312, 72, 444, 288];
                      myTextFrameC.contents = "This is story 3.";
                  }
                  function mySnippet(){
                      //<fragment>
                      if(app.documents.length != 0){
                          if(app.documents.item(0).stories.length != 0){
                              myExportAllText(app.documents.item(0).name);
                          }
                      }
                      //</fragment>
                  }
                  function myTeardown(){
                  }
                  //<fragment>
                  function myExportAllText(myDocumentName){
                      var myStory;
                      //File name for the exported text. Fill in a valid file path on your system.
                      var myFileName = "/c/test.txt";
                      //If you want to add a separator line between stories, set myAddSeparator to true.
                      var myAddSeparator = true;
                      var myNewDocument = app.documents.add();
                      var myDocument = app.documents.item(myDocumentName);
                      var myTextFrame = myNewDocument.pages.item(0).textFrames.add({geometricBounds:myGetBounds(myNewDocument, myNewDocument.pages.item(0))});
                      var myNewStory = myTextFrame.parentStory;
                      for(myCounter = 0; myCounter < myDocument.stories.length; myCounter++){
                          myStory = myDocument.stories.item(myCounter);
                          //Export the story as tagged text.
                          myStory.exportFile(ExportFormat.taggedText, File(myFileName));
                          //Import (place) the file at the end of the temporary story.
                          myNewStory.insertionPoints.item(-1).place(File(myFileName));
                          //If the imported text did not end with a return, enter a return
                          //to keep the stories from running together.
                          if(myCounter != myDocument.stories.length -1){
                              if(myNewStory.characters.item(-1).contents != "\r"){
                                  myNewStory.insertionPoints.item(-1).contents = "\r";
                              }
                              if(myAddSeparator == true){
                                  myNewStory.insertionPoints.item(-1).contents = "----------------------------------------\r";
                              }
                          }
                      }
                      myNewStory.exportFile(ExportFormat.taggedText, File("/c/test.txt"));
                      myNewDocument.close(SaveOptions.no);
                  }
                  //</fragment>
                  function myGetBounds(myDocument, myPage){
                      var myPageWidth = myDocument.documentPreferences.pageWidth;
                      var myPageHeight = myDocument.documentPreferences.pageHeight
                      if(myPage.side == PageSideOptions.leftHand){
                          var myX2 = myPage.marginPreferences.left;
                          var myX1 = myPage.marginPreferences.right;
                      }
                      else{
                          var myX1 = myPage.marginPreferences.left;
                          var myX2 = myPage.marginPreferences.right;
                      }
                      var myY1 = myPage.marginPreferences.top;
                      var myX2 = myPageWidth - myX2;
                      var myY2 = myPageHeight - myPage.marginPreferences.bottom;
                      return [myY1, myX1, myY2, myX2];
                  }

                  • 6. Re: Export by Paragraph Style to text file
                    [Jongware] Most Valuable Participant

                    Beginners' books? I wouldn't know, I've been programming as a hobby for some 20-odd years, and javascript itself is "just another language".

                    I still wrestle with InDesign objects, and I debug by simply throwing 'alert ("x is now "+x)' all over the place.

                    • 7. Re: Export by Paragraph Style to text file
                      [Jongware] Most Valuable Participant

                      -- someTextFrame.exportFile (ExportFormat.textType, File("/Users/robot/Desktop/TestDocument.inx"));

                       

                      Shouldn't that be ExportFormat.INDESIGN_INTERCHANGE for an inx file?

                      • 8. Re: Export by Paragraph Style to text file
                        FivePicaPica Level 4

                        I'm going to mark this as answered, since I got it to work as well as I need it to.

                         

                        ExportFormat.INDESIGN_INTERCHANGE exports the complete file, not just the TextFrame, and it's quicker to just cut and paste. But it's a place to start for when I attempt to write another script.

                         

                        Thanks so much for all the help.