r/GoogleAppsScript • • 15d ago

Guide Script to standardize formatting and bulk-apply custom heading styles across Google Docs & Drive folders

Cross-posting a workflow I shared in r/googledocs for teams trying to standardize formatting and enforce a consistent style guide across Google Docs without a built-in Workspace "brand kit."

Instead of manually updating default styles on every user's machine, this uses a single Master Style Guide Doc bound to an Apps Script that pushes typography, spacing, and an HSL-generated color palette to individual docs or recursively across an entire Google Drive folder.

What the script covers:

  • Custom onOpen() menu (Org Styles): Apply styles to the active Master Doc, prompt for a target Doc URL/ID, or prompt for a Drive Folder URL/ID.
  • Recursive DriveApp traversal: Walks through a root folder and all nested subfolders (MimeType.GOOGLE_DOCS), tracks successes, and catches/logs files missing Editor access instead of halting execution.
  • HSL-to-Hex color generation (hslToHex_): Derives a cohesive color hierarchy for TITLE, SUBTITLE, NORMAL, and HEADING1–HEADING6 from a single base hue constant (THEME_HUE).
  • Paragraph & list styling: Normalizes font family (Open Sans), line spacing (1.15), and spacingBefore (10pt) across both getParagraphs() and getListItems().

Full Code (Code.gs)

/**
 * Creates a custom menu in Google Docs when the document opens.
 */
function onOpen() {
  DocumentApp.getUi()
    .createMenu('Org Styles')
    .addItem('Apply Default Styles', 'applyStylesToExistingDocument')
    .addItem('Apply Styles to Another Document...', 'promptAndApplyStyles')
    .addItem('Apply Styles to Folder...', 'promptAndApplyStylesToFolder')
    .addToUi();
}

/**
 * Prompts the user for a Google Doc URL or ID and applies default styles to it.
 */
function promptAndApplyStyles() {
  const ui = DocumentApp.getUi();
  const response = ui.prompt(
    'Apply Default Styles to Another Document',
    'Paste the Google Doc URL or Document ID:',
    ui.ButtonSet.OK_CANCEL
  );

  if (response.getSelectedButton() !== ui.Button.OK) {
    return;
  }

  const input = response.getResponseText().trim();
  const docId = extractDocumentId_(input);

  if (!docId) {
    ui.alert('Invalid Input', 'Could not find a valid Google Doc ID in your input.', ui.ButtonSet.OK);
    return;
  }

  try {
    applyStylesToExistingDocument(docId);
    ui.alert('Styles Applied', 'Default styles have been applied to the target document.', ui.ButtonSet.OK);
  } catch (err) {
    console.error(`Failed to apply styles to document ${docId}: ${err.message}`);
    ui.alert('Error', 'Could not update the document. Verify the ID/URL and ensure you have Editor access.', ui.ButtonSet.OK);
  }
}

/**
 * Prompts the user for a Google Drive folder URL or ID and batch-formats
 * all Google Docs inside that folder and its subfolders.
 */
function promptAndApplyStylesToFolder() {
  const ui = DocumentApp.getUi();
  const response = ui.prompt(
    'Apply Default Styles to Folder',
    'Paste the Google Drive Folder URL or Folder ID:',
    ui.ButtonSet.OK_CANCEL
  );

  if (response.getSelectedButton() !== ui.Button.OK) {
    return;
  }

  const input = response.getResponseText().trim();
  const folderId = extractFolderId_(input);

  if (!folderId) {
    ui.alert('Invalid Input', 'Could not find a valid Google Drive Folder ID in your input.', ui.ButtonSet.OK);
    return;
  }

  try {
    const summary = applyStylesToFolder_(folderId);
    let message = `Updated ${summary.updatedCount} Google Doc(s) in "${summary.folderName}".`;
    if (summary.failedCount > 0) {
      message += `\n\nSkipped ${summary.failedCount} document(s) due to errors or missing Editor access:\n- ${summary.skippedFiles.join('\n- ')}`;
    }
    ui.alert('Batch Formatting Complete', message, ui.ButtonSet.OK);
  } catch (err) {
    console.error(`Failed to process folder ${folderId}: ${err.message}`);
    ui.alert('Error', 'Could not access the folder. Verify the URL/ID and ensure you have access.', ui.ButtonSet.OK);
  }
}

/**
 * Applies default styles to all Google Docs inside the given Drive folder
 * and all of its subfolders recursively.
 *
 * @param {string} folderId The Google Drive folder ID.
 * @returns {{folderName: string, updatedCount: number, failedCount: number, skippedFiles: string[]}} Summary of processed files.
 */
function applyStylesToFolder_(folderId) {
  const rootFolder = DriveApp.getFolderById(folderId);
  const folderName = rootFolder.getName();

  let updatedCount = 0;
  let failedCount = 0;
  const skippedFiles = [];

  console.log(`Starting recursive batch style update for folder "${folderName}" (${folderId})...`);

  function processFolder(folder) {
    const files = folder.getFilesByType(MimeType.GOOGLE_DOCS);
    while (files.hasNext()) {
      const file = files.next();
      try {
        applyStylesToExistingDocument(file.getId());
        updatedCount++;
      } catch (err) {
        failedCount++;
        skippedFiles.push(file.getName());
        console.warn(`Skipped "${file.getName()}" (${file.getId()}): ${err.message}`);
      }
    }

    const subfolders = folder.getFolders();
    while (subfolders.hasNext()) {
      processFolder(subfolders.next());
    }
  }

  processFolder(rootFolder);

  console.log(`Batch update complete for "${folderName}". Updated: ${updatedCount}, Failed: ${failedCount}`);
  return { folderName, updatedCount, failedCount, skippedFiles };
}

/**
 * Extracts a Google Doc ID from a full URL or returns a raw ID if valid.
 */
function extractDocumentId_(input) {
  if (!input) return null;
  const urlMatch = input.match(/\/d\/([a-zA-Z0-9-_]+)/) || input.match(/[?&]id=([a-zA-Z0-9-_]+)/);
  if (urlMatch) return urlMatch[1];
  if (/^[a-zA-Z0-9-_]+$/.test(input)) return input;
  return null;
}

/**
 * Extracts a Google Drive folder ID from a full URL or returns a raw ID if valid.
 */
function extractFolderId_(input) {
  if (!input) return null;
  const urlMatch = input.match(/\/folders\/([a-zA-Z0-9-_]+)/) || input.match(/[?&]id=([a-zA-Z0-9-_]+)/);
  if (urlMatch) return urlMatch[1];
  if (/^[a-zA-Z0-9-_]+$/.test(input)) return input;
  return null;
}

/**
 * Converts HSL color values to a CSS hex string required by DocumentApp.
 */
function hslToHex_(h, s, l) {
  const sat = s / 100;
  const light = l / 100;
  const a = sat * Math.min(light, 1 - light);

  const channel = n => {
    const k = (n + h / 30) % 12;
    const value = light - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
    return Math.round(255 * value).toString(16).padStart(2, '0');
  };

  return '#' + channel(0) + channel(8) + channel(4);
}

const THEME_HUE = 25; // Adjust 0-360 to change your color family (25 = warm brown, 210 = blue, etc.)

const HEADING_STYLES = {
  [DocumentApp.ParagraphHeading.TITLE]: { fontSize: 26, color: hslToHex_(THEME_HUE, 55, 24), bold: true, italic: false },
  [DocumentApp.ParagraphHeading.SUBTITLE]: { fontSize: 15, color: hslToHex_(THEME_HUE, 32, 40), bold: false, italic: false },
  [DocumentApp.ParagraphHeading.NORMAL]: { fontSize: 11, color: hslToHex_(THEME_HUE, 6, 15) },
  [DocumentApp.ParagraphHeading.HEADING1]: { fontSize: 20, color: hslToHex_(THEME_HUE, 55, 28), bold: true, italic: false },
  [DocumentApp.ParagraphHeading.HEADING2]: { fontSize: 16, color: hslToHex_(THEME_HUE, 50, 34), bold: true, italic: false },
  [DocumentApp.ParagraphHeading.HEADING3]: { fontSize: 14, color: hslToHex_(THEME_HUE, 45, 39), bold: true, italic: false },
  [DocumentApp.ParagraphHeading.HEADING4]: { fontSize: 12, color: hslToHex_(THEME_HUE, 35, 32), bold: true, italic: false },
  [DocumentApp.ParagraphHeading.HEADING5]: { fontSize: 11, color: hslToHex_(THEME_HUE, 30, 34), bold: true, italic: true },
  [DocumentApp.ParagraphHeading.HEADING6]: { fontSize: 11, color: hslToHex_(THEME_HUE, 25, 36), bold: false, italic: true }
};

/**
 * Applies standard formatting to all paragraphs and list items in an existing document.
 */
function applyStylesToExistingDocument(docId) {
  const doc = docId
    ? DocumentApp.openById(docId)
    : DocumentApp.getActiveDocument();

  if (!doc) {
    throw new Error('Could not access the target document. Verify the document ID or run from a bound document.');
  }

  const body = doc.getBody();
  const paragraphs = body.getParagraphs();
  const listItems = body.getListItems();
  const normalStyle = HEADING_STYLES[DocumentApp.ParagraphHeading.NORMAL];

  console.log(`Applying styles to "${doc.getName()}" (${paragraphs.length} paragraphs, ${listItems.length} list items)...`);

  paragraphs.forEach(para => {
    para.setLineSpacing(1.15);
    para.setSpacingBefore(10);

    if (para.getText().length > 0) {
      const text = para.editAsText();
      text.setFontFamily('Open Sans');

      const headingStyle = HEADING_STYLES[para.getHeading()];
      if (headingStyle) {
        text.setFontSize(headingStyle.fontSize);
        text.setForegroundColor(headingStyle.color);
        if (typeof headingStyle.bold === 'boolean') {
          text.setBold(headingStyle.bold);
        }
        if (typeof headingStyle.italic === 'boolean') {
          text.setItalic(headingStyle.italic);
        }
      }
    }
  });

  listItems.forEach(item => {
    item.setLineSpacing(1.15);
    if (item.getText().length > 0) {
      const text = item.editAsText();
      text.setFontFamily('Open Sans');
      text.setFontSize(normalStyle.fontSize);
      text.setForegroundColor(normalStyle.color);
    }
  });

  console.log(`Finished updating styles for "${doc.getName()}".`);
}

Full walkthrough in r/googledocs

6 Upvotes

4 comments sorted by

2

u/TangeloHappy4687 3d ago

One edge case to check: list items get the normal text colour and size, but not the heading styles applied to paragraphs. If a heading is formatted as a list item, it may lose the intended hierarchy.

2

u/Janaje_Ushae 2d ago

One thing to watch: setSpacingBefore(10) runs on every paragraph, so it adds space before normal body text as well as headings. If the goal is heading separation, you could apply that only when getHeading() isn’t NORMAL.

1

u/Uriah_Thomas36 3d ago

The recursive folder traversal and per-file error handling are useful touches. One assumption worth checking is that setting text style on a paragraph won't override existing inline formatting, such as bold or links, in the docs being batch-updated.