How to determine if text is written in the last row of the page with apps script

Viewed 27

I'm using Apps Script to fill a google doc with many paragraphs. Each paragraph has its header. Because the text is filled by itself by the script, sometimes a certain paragraph's header starts in the page's last row. I'm trying to avoid that.

I want to spot whether the last row I append in the paragraph before is at the end of the page (or even maybe in the last quarter of it) and if it is, to make a page break and move the next header to a new page. Is there a way to do so?

Thank for the help.

1 Answers

Unfortunately this is currently not possible. It is not even possible which page the paragraph is contained in at all ( see respective feature request)

What you can do instead is to specify that all lines of a paragraph (including) shall be kept together

enter image description here

To do it programmaticaly:

Sample (provided you know the index of the new paragraph):

  var doc = Docs.Documents.get(documentId);
  var paragraph = doc.body.content[paragraphIndex];
  var request = {
    "updateParagraphStyle": {
      "paragraphStyle": {
        "keepWithNext": true,
      },
      "fields": "keepLinesTogether",
      "range": {
        "startIndex": paragraph.startIndex,
        "endIndex": paragraph.endIndex
      }
    }
  }
  Docs.Documents.batchUpdate({ 'requests': [request] },documentId);
Related