Search code examples
javascriptadobe-indesign

Indesign script: set background image behind a text with a certain paragraph style


I was searching for a solution in Indesign to set a background image behind a text with a certain paragraph style. Unfortunately I did not find any yet. So I thought maybe you can help me out with a script where you:

  • assign a paragraph style (let's say "chapter_head")

  • search for its encounter in the whole document.

  • cut text of the found item and paste it with the same style(or a copy of the style) into a new textframe

  • load a picture behind the textframe ("small-frame.ai")

  • group, and paste it to the position where we cut the text out

  • repeat with all found elements

Thanks in advance! Edit: here as requested a picture of what I am aiming at

enter image description here


Solution

  • Here you go.

    // find all headers with style 'header'
    app.findGrepPreferences = NothingEnum.nothing;
    app.findGrepPreferences.findWhat = '^.+$';
    app.findGrepPreferences.appliedParagraphStyle = 'header';
    var headers = app.activeDocument.findGrep();
    
    // store contents of the headers in the array 'contents'
    var contents = [];
    while (headers.length) contents.push(headers.shift().contents);
    
    // replace all the headers with placeholder from clipboard
    app.changeGrepPreferences.changeTo = '~C';
    app.activeDocument.changeGrep();
    
    // change all '#placeholder#' with contents of the headers
    app.findGrepPreferences = NothingEnum.nothing;
    app.findGrepPreferences.findWhat = '#placeholder#';
    var placeholders = app.activeDocument.findGrep();
    while (contents.length) placeholders.pop().contents = contents.pop();
    

    The script finds all the paragraphs with style 'header', changes them with contents of clipboard (a group: image + text '#placeholder#'), then finds and changes all the texts '#placeholder#' with contents of the headers.

    Before:

    enter image description here

    After:

    enter image description here