0
votes

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
1
unfortunatelly no. The condition ele.getParent().getParent().getType() === DocumentApp.ElementType.BODY_SECTION is not true although the placeholder is found - Radek
sure, code looks a bit overengineered, take a look at stackoverflow.com/questions/54499394/… which may be better duplicate - Kos
@Kos yes, this one helped. Thank you. - Radek

1 Answers

0
votes

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)