Apps Script that Cleans doc add spacing above each heading

This Google Apps Script demonstrates the power of automation in Google Workspace. Whether you’re managing files in Google Drive or cleaning up messy Google Docs, this script offers a simple yet effective solution.

Here’s a Google Apps Script function that performs the following tasks on a Google Doc:

  1. Adds spacing above all heading elements: Adds a specific amount of spacing above headings (H1, H2, H3, etc.).
  2. Applies 1.5 line spacing to the entire document.

Script:

function formatDocumentSpacing() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();

// Adjust spacing above headings
const headings = [
DocumentApp.ParagraphHeading.HEADING1,
DocumentApp.ParagraphHeading.HEADING2,
DocumentApp.ParagraphHeading.HEADING3,
DocumentApp.ParagraphHeading.HEADING4,
DocumentApp.ParagraphHeading.HEADING5,
DocumentApp.ParagraphHeading.HEADING6
];

const spacingAbove = 20; // Spacing above in points

// Iterate through all paragraphs
const paragraphs = body.getParagraphs();
for (const paragraph of paragraphs) {
const headingType = paragraph.getHeading();
if (headings.includes(headingType)) {
paragraph.setSpacingBefore(spacingAbove); // Add spacing above headings
}

// Apply 1.5 line spacing to each paragraph
paragraph.setLineSpacing(1.5);
}

Logger.log("Document formatting updated: spacing above headings and 1.5 line spacing applied.");
}

How It Works:

  1. Headings Spacing:
    • The script identifies all paragraphs with headings (H1 to H6).
    • It applies setSpacingBefore(spacingAbove) to add spacing above these headings.
  2. Line Spacing:
    • The script iterates through all paragraphs and applies setLineSpacing(1.5) to set the line spacing to 1.5 for the entire document.

Usage:

  1. Open your Google Doc.
  2. Open the Apps Script editor:
    • Extensions > Apps Script.
  3. Paste the script above into the editor and save it.
  4. Run the formatDocumentSpacing function:
    • Click Run in the Apps Script editor or assign it to a menu option or button.

Customization:

  • Spacing Above Headings: Adjust const spacingAbove = 20; to increase or decrease the spacing (measured in points).
  • Line Spacing: Adjust paragraph.setLineSpacing(1.5); to change the line spacing multiplier (e.g., 2 for double spacing).

Example Output:

  • Headings (H1, H2, etc.): Will have 20 points of spacing above them.
  • Body Text: Will have 1.5 line spacing applied throughout.