Google Apps Script that inserts page breaks in a Google Doc just before each H3 element

Google Apps Script that inserts page breaks in a Google Doc just before each H3 element, you can follow this approach. This script iterates through the document’s elements, identifies H3 headings, and inserts page breaks immediately before each H3 element.

function insertPageBreaksBeforeH3() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var numChildren = body.getNumChildren();
  
  for (var i = 0; i < numChildren; i++) {
    var child = body.getChild(i);
    if (child.getType() === DocumentApp.ElementType.PARAGRAPH) {
      var paragraph = child.asParagraph();
      // Check if the paragraph is an H3 heading
      if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING3) {
        // Insert a page break before this H3 element if it's not the first element of the document
        if (i > 0) {
          body.insertPageBreak(i - 1);
          i++; // Increment i because we've added a new element, shifting the indices
          numChildren++; // Increment numChildren to account for the new page break
        }
      }
    }
  }
}

How to Use This Script:

  1. Open your Google Doc.
  2. Go to Extensions > Apps Script.
  3. Delete any code in the script editor and paste the above script.
  4. Save the script with a name, for example, InsertPageBreaksBeforeH3.
  5. Run the script by clicking the play (▶️) button or selecting the function insertPageBreaksBeforeH3 from the dropdown next to the play button and then clicking it.

This script checks each paragraph to determine if it’s styled as an H3 heading. If it finds an H3 heading and it’s not the very first element in the document, it inserts a page break immediately before the H3 heading. The script includes checks to ensure that the element indices and count are updated appropriately after inserting a page break, to avoid skipping any elements during iteration.

Please note, if your document contains elements other than paragraphs (e.g., tables, images) directly before an H3 heading, additional logic may be required to handle these cases effectively.