Replace a text keyword with a “Page Break” element in Apps Script

蓝咒 提交于 2021-02-10 13:40:06

问题


I want to replace a specific text keyword with a page break. Here's what I've tried:

body.findText("%PAGE_BREAK%").getElement().appendPageBreak()

and

body.replaceText("%PAGE_BREAK%", "").asBody().appendPageBreak()

I'm trying to edit existing documents which have %page_break% somewhere and replace it with an actual page break element.


回答1:


The following will suffice under the assumption that "%page_break%" appears either at the end of a paragraph, or in a paragraph of its own. The script searches the text for this pattern, and appends a PageBreak element to the end of the element (paragraph) containing the found text. Then it removes the pattern.

function pageBreaks() {
  var searchPattern = "%page_break%";
  var body = DocumentApp.getActiveDocument().getBody();
  var found = body.findText(searchPattern); 
  while (found) {
    found.getElement().getParent().appendPageBreak();
    found = body.findText(searchPattern, found);
  }
  body.replaceText(searchPattern, "");
}

It does not make much sense to place page breaks inside of paragraphs, but Google Docs supports this, and there is Paragraph.insertPageBreak method for that. However, to use it you would need to first split the Text element containing the search pattern so that a page break can go in between two Texts. (A Text element cannot contain any other elements.)



来源:https://stackoverflow.com/questions/49421966/replace-a-text-keyword-with-a-page-break-element-in-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!