0

I am using Google document a template for generating PDFs files. The template contains placeholders - **name-of-placeholder** The placeholder is later on replaced with a value of corresponding variable. Now I need to replace a placeholder with a table.

Could someone suggest how to replace a text with a table using Google Application Script?

The template looks like that


enter image description here


I need to replace text detaily-programu with a table.

I managed to add a table

at the end of the document

 // table method c.1
 //Add a table in document
   var table = body.appendTable()

at the point where is should be by replacing empty table

// table method c.2  
// var searchType = DocumentApp.ElementType.TABLE
// var table = body.findElement(searchType).getElement()
// table.clear()

I would prefer to be able to replace the placeholder with a table. But I cannot make it work. .findText() finds the text but I do not know how to append the table after the element .findText() found. And of course delete the element.

// table method c.3
var text = body.findText("detaily-programu").getElement()
//var table = text.asParagraph().appendTable() // Exception: TEXT can't be cast to PARAGRAPH.
//var table = text.appendTable()                 // TypeError: text.appendTable is not a function
Radek
  • 13,813
  • 52
  • 161
  • 255
  • Does this answer your question? [How to append table after specific text in google docs using google apps script?](https://stackoverflow.com/questions/57641087/how-to-append-table-after-specific-text-in-google-docs-using-google-apps-script) – Kos Sep 16 '21 at 21:15
  • unfortunatelly no. The condition `ele.getParent().getParent().getType() === DocumentApp.ElementType.BODY_SECTION` is not true although the placeholder is found – Radek Sep 16 '21 at 21:35
  • 1
    sure, code looks a bit overengineered, take a look at https://stackoverflow.com/questions/54499394/replace-search-text-with-table which may be better duplicate – Kos Sep 16 '21 at 22:04
  • @Kos yes, this one helped. Thank you. – Radek Sep 16 '21 at 22:58

1 Answers1

0

Thanks to Kos and this answer I was able to do exactly what I wanted. The code is

  var rgel= args.body.findText("detaily-programu")
  var element=rgel.getElement()
  var childIndex= args.body.getChildIndex(element.getParent())
  args.body.getChild(childIndex).asText().setText('')
  var table = args.body.insertTable(childIndex)
Radek
  • 13,813
  • 52
  • 161
  • 255