javascriptscriptingjsxadobe-indesign

Change textFrame content with given styled text


Let's say I have a given TextFrame, and I want to completely substitute its content with my own text - which is going to contain some text in bold and a newline - how should I go about it?

The final text should be something like:

<b>WORD</b><br>
NEW WORD

What I've tried so far:

var frame = app.activeDocument.textFrames.item("scr-hello");

var myStringsAndStyles = [
    {
      contents: "WORD",
      characterStyle: bold
    },
    {
      contents: "NEW WORD",
      characterStyle: none
    }
  ];

  with (frame.insertionPoints ) {
    for ( var i = 0, arrlength = myStringsAndStyles.length; i < arrlength; i++ ) {
      lastItem().properties = {
        contents: myStringsAndStyles[i].contents,
        appliedCharacterStyle: myStringsAndStyles[i].characterStyle
      }
    }
  }

The problem is:


Solution

  • It can be done this way:

    var frame = app.activeDocument.textFrames.item('scr-hello');
    frame.contents = 'WORD\nNEW WORD';              // fill the frame with the text
    var line = frame.parentStory.texts[0].lines[0]; // get the first line from the frame
    line.fontStyle = 'Bold';                        // assign Bold style
    

    But you have to make sure that the font has Bold style. Some fonts have no additional styles.

    Just in case, here is the extended example with character styles:

    var doc = app.activeDocument;
    
    // get the styles
    var style_none = doc.characterStyles[0]; // '[None]'
    var style_bold = doc.characterStyles.item('Bold');
    
    // create the 'Bold' style if there is no such style
    if (!style_bold.isValid) {
        style_bold = doc.characterStyles.add();
        style_bold.name = 'Bold';
        style_bold.fontStyle = 'Bold';
    }
    
    // get the frame and change its contents
    var frame = app.activeDocument.textFrames.item('scr-hello');
    frame.contents = 'WORD\nNEW WORD';
    var story = frame.parentStory;
    
    // remove the old formatting
    story.texts.everyItem().appliedCharacterStyle = style_none;
    story.texts.everyItem().clearOverrides();
    
    // apply the 'Bold' style to the first line
    var line = story.texts[0].lines[0].appliedCharacterStyle = style_bold;