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:
- Adds spacing above all heading elements: Adds a specific amount of spacing above headings (
H1
,H2
,H3
, etc.). - 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:
- Headings Spacing:
- The script identifies all paragraphs with headings (
H1
toH6
). - It applies
setSpacingBefore(spacingAbove)
to add spacing above these headings.
- The script identifies all paragraphs with headings (
- 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.
- The script iterates through all paragraphs and applies
Usage:
- Open your Google Doc.
- Open the Apps Script editor:
Extensions > Apps Script
.
- Paste the script above into the editor and save it.
- Run the
formatDocumentSpacing
function:- Click
Run
in the Apps Script editor or assign it to a menu option or button.
- Click
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.