inDesign Script: Get Text and Page number of Text styled with a certain Paragraph Style using JavaScript

5.7k Views Asked by At

I have an inDesign document with 10 pages filled with text. The text is styled with different Paragraph Styles, of which some are relevant for building a custom table of contents.

There are two relevant Paragraph Styles, "Header1" and "Header2" from which I am trying to build my own Table of Contents, which I want to export in a text file.

The relevant information I need to get is the text which is styled with "Header1" and "Header2" and the corresponding page number.

I tried to achieve this via GREP and was halfway successful, but GREP scans the whole document and not page by page.

Is there a way to go through all styled texts by Paragraph Style page by page?

Thanks in advance!

2

There are 2 best solutions below

0
On

Yes.

Give a look into the Object model of the InDesign API.

You have the class Pages so iterate over all Pages, using method length

Then, inside this loop, for each page get all the TextFrames

For each textFrame use the Class Paragraph to iterate over each TextFrame

Inside each paragraph, get the attributes you want.

0
On

If you don't want to use GREP, you can iterate through each paragraph of the story you are interested in collecting paragraphs with a certain style applied to them.

In the sample code below I collected the paragraphs in the para_with_style variable:

var doc = app.activeDocument;

var story = doc.stories[0];

// Get every paragraph in `story` (using `everyItem().getElements()` is more efficient)
var paras = story.paragraphs.everyItem().getElements();

// Collect every paragraph with a certain paragraph style
var applied_style = doc.paragraphStyles.itemByName('style-name');
var paras_with_style = [];
for (var i=0,l=paras.length; i<l; i++) {
   var para = paras[i];
   if (para.appliedParagraphStyle == applied_style) {
      paras_with_style.push(para);
   }
}

// Do something with each `para` in `paras_with_style`