问题
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