将文本关键字替换为“分页符",Apps脚本中的元素 [英] Replace a text keyword with a "Page Break" element in Apps Script

查看:38
本文介绍了将文本关键字替换为“分页符",Apps脚本中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用分页符替换特定的文本关键字.这是我尝试过的:

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

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

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

我正在尝试编辑在某些地方具有%page_break%的现有文档,并将其替换为实际的分页符元素.

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

推荐答案

在%page_break%"出现在段落末尾或段落本身的假设下,下面的内容就足够了.该脚本在文本中搜索此模式,然后将PageBreak元素追加到包含找到的文本的元素(段落)的末尾.然后将其删除.

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, "");
}

将分页符放在段落中没有多大意义,但是Google文档支持此功能,并且有

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.)

这篇关于将文本关键字替换为“分页符",Apps脚本中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆