簡體   English   中英

在 Google Apps 腳本中的文本前插入換行符

[英]Insert Line breaks before text in Google Apps Script

我需要在 Google 文檔中的某些文本之前插入一些換行符。

嘗試了這種方法,但得到錯誤:

var body = DocumentApp.getActiveDocument().getBody();
var pattern = "WORD 1";
var found = body.findText(pattern);
var parent = found.getElement().getParent();
var index = body.getChildIndex(parent);
// or parent.getChildIndex(parent);
body.insertParagraph(index, "");

關於如何做到這一點的任何想法?

感謝幫助!

例如,作為一個簡單的修改,如何修改你上一個問題中的https://stackoverflow.com/a/65745933的腳本?

在這種情況下,使用InsertTextRequest代替 InsertPageBreakRequest。

修改后的腳本:

請將以下腳本復制粘貼到 Google Document 的腳本編輯器中,並設置 searchPattern。 並且, 請在 Advanced Google services 中啟用 Google Docs API

function myFunction() {
  const searchText = "WORD 1";  // Please set text. This script inserts the pagebreak before this text.
  
  // 1. Retrieve all contents from Google Document using the method of "documents.get" in Docs API.
  const docId = DocumentApp.getActiveDocument().getId();
  const res = Docs.Documents.get(docId);
  
  // 2. Create the request body for using the method of "documents.batchUpdate" in Docs API.
  let offset = 0;
  const requests = res.body.content.reduce((ar, e) => {
    if (e.paragraph) {
      e.paragraph.elements.forEach(f => {
        if (f.textRun) {
          const re = new RegExp(searchText, "g");
          let p = null;
          while (p = re.exec(f.textRun.content)) {
            ar.push({insertText: {location: {index: p.index + offset},text: "\n"}});
          }
        }
      })
    }
    offset = e.endIndex;
    return ar;
  }, []).reverse();
  
  // 3. Request the request body to the method of "documents.batchUpdate" in Docs API.
  Docs.Documents.batchUpdate({requests: requests}, docId);
}

結果:

使用上述腳本時,會得到以下結果。

從:

在此處輸入圖像描述

至:

在此處輸入圖像描述

筆記:

  • 當您不想像上一個問題那樣直接使用高級 Google 服務時,請修改https://stackoverflow.com/a/65745933的第二個腳本如下。

    •  ar.push({insertPageBreak: {location: {index: p.index + offset}}});
    •  ar.push({insertText: {location: {index: p.index + offset},text: "\n"}});

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM