Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to place multiple paragraphs from a different document at a placeholder in my document

I want to place multiple paragraphs from a different document at a placeholder in my document.

The placeholder in the final document is "{plc}".

I've tried this:

  var docNew = DocumentApp.openById(docNewID);
  var docNewBody = docNew.getBody();

  var docTempBody = DocumentApp.openById(docTempID).getBody();
  var docTempPars = docTempBody.getParagraphs();

  var range = docNewBody.findText("{plc}").getElement().getParent().getChildIndex();
  docTempPars.forEach(function(p2){
    docNewBody.insertParagraph(range, p2);
    var range = range + 1;
    })

But nothing at all is added. Can someone help out please?

like image 484
bandwagoner Avatar asked Dec 09 '25 00:12

bandwagoner


1 Answers

I believe your goal as follows.

  • You want to replace {plc} in docNewBody with the all paragraphs of docTempBody using Google Apps Script.
  • From your script, there is only one {plc} in the document.

Modification points:

  • getChildIndex(child) has the argument of child.
    • In this case, I think that an error occurs at var range = docNewBody.findText("{plc}").getElement().getParent().getChildIndex();.
  • In your script, {plc} is not removed.
  • When the paragraph is inserted, please use copy().
  • In order to achieve your goal, I would like to propose the following flow.
    1. Retrieve all paragraphs from docTempBody.
    2. Retrieve the child index of {plc}.
    3. Remove {plc}.
    4. Insert the paragraphs.

When your script is modified, it becomes as follows.

Modified script:

function myFunction() {
  var docNew = DocumentApp.openById(docNewID);
  var docNewBody = docNew.getBody();
  
  // 1. Retrieve all paragraphs from `docTempBody`.
  var docTempBody = DocumentApp.openById(docTempID).getBody();
  var docTempPars = docTempBody.getParagraphs();
  console.log(docTempPars.length)

  // 2. Retrieve the child index of `{plc}`.
  var element = docNewBody.findText("{plc}").getElement().getParent();
  var range = docNewBody.getChildIndex(element);

  // 3. Remove `{plc}`.
  element.removeFromParent();
  
  // 4. Insert the paragraphs.
  docTempPars.forEach(function(p2){
    docNewBody.insertParagraph(range++, p2.copy());
  });
}

References:

  • getChildIndex(child)
  • copy()
like image 99
Tanaike Avatar answered Dec 11 '25 22:12

Tanaike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!