基準点となる文字列を含んだパラグラフの次に新しいパラグラフを挿入する方法を考えます。新しいパラグラフの中身はダイアログボックスで入力した文字列とします。
function myFunction() { var body = DocumentApp.getActiveDocument().getBody(); var paragraphs = body.getParagraphs(); for (var i = 0; i < paragraphs.length; i++) { var paragraph = paragraphs[i]; var index = i; var text = paragraph.getText(); if(text === 'key paragraph'){ Logger.log('index %s text %s', index, text); var child = paragraph; } } var childIndex = body.getChildIndex(child); Logger.log('childIndex %s', childIndex); //input text to insert var ui = DocumentApp.getUi(); var response = ui.prompt( '挿入する文字列を記入する。', ui.ButtonSet.OK_CANCEL); // Process the user's response. var button = response.getSelectedButton(); var textToInsert = response.getResponseText(); //キャンセルならスクリプト終了 if (button !== ui.Button.OK) { return; } //insertParagraph body.insertParagraph(childIndex + 1, textToInsert); } //メニューを追加 function onOpen(e) { DocumentApp.getUi() .createMenu('GAS') .addItem('insert paragraph', 'myFunction') .addToUi(); }
まず、DocumentAppでBodyとその下のparagraphsを取ってきます。各paragraphの中の文字列はgetText()で取れるので、基準点となる文字列が含まれるparagraphを探します。上の例では、paragraphの文字列が「key paragraph」であるという条件で該当するparagraphを指定しました。
基準点となるparagraphオブジェクトが見つかったら、body.getChildIndex(paragraph)のように引数として渡してやると、bodyに対するchildIndexが返ってきます。
基準となるparagraphの childIndexが求まったら、そのparagraphの前に挿入する場合は childIndex を、そのparagraphの後ろに挿入する場合はchildIndex+1を、insertParagraphの引数に渡します。
挿入する文字列を入力するのに使ったダイアログボックスですが、V8エンジンではBrowser.inputbox()が動かないのか、UI.prompt()を使うと動きました。UI.prompt()は返ってきたresponseにさらにgetResponseText()しないとテキストが取れません。
ドキュメントのメニューからスクリプトを動作せさせる工程はGoogle Apps Scriptを使った独自メニューの作り方を参照しました。
テンプレートを別ファイルで用意する場合はGoogle Apps Scriptで議事録テンプレ作成を楽にしたが参考になります。