Building a Google Docs script to format paragraphs with custom styling options?

I want to build a Google Apps Script that can format text in Google Docs with specific paragraph settings. The default paragraph styles in Docs are limited so I need something custom.

My formatting requirements are:

  • 4 cm left margin indentation
  • Arial font at size 10 points
  • Single line spacing
  • Extra 1.5 spacing above paragraphs
  • Full text justification

I found some code online that creates a custom menu for text formatting but I don’t know how to modify it for my needs. I’m pretty new to this stuff.

Here’s what I have so far:

// Creates menu when document opens
function onOpen() {
  DocumentApp.getUi()
  .createMenu('Format Tools')
  .addItem('Apply Citation Format', 'applyCitationFormat')
  .addToUi();
}

// Style configuration object
var citationStyle = {
  bold: false,
  backgroundColor: "#F0F0F0",
  fontFamily: DocumentApp.FontFamily.COURIER_NEW
};

// Gets selected text and processes it
function processSelection(handlePartial, handleComplete) {
  var currentSelection = DocumentApp.getActiveDocument().getSelection();
  if (currentSelection) {
    var selectedItems = currentSelection.getSelectedElements();
    for (var j = 0; j < selectedItems.length; j++) {
      var item = selectedItems[j];
      if (item.getElement().editAsText) {
        var textElement = item.getElement();
        if (item.isPartial()) {
          var startPos = item.getStartOffset();
          var endPos = item.getEndOffsetInclusive();
          return handlePartial(item, textElement, startPos, endPos);
        } else {
          return handleComplete(item, textElement);
        }
      }
    }
  }
}

// Main function triggered by menu
function applyCitationFormat() {
  return processSelection(
    formatPartialText.bind(this, citationStyle),
    formatFullText.bind(this, citationStyle)
  );
}

// Formats selected text range
function formatPartialText(styleConfig, item, textEl, start, end) {
  textEl.setFontFamily(start, end, styleConfig.fontFamily);
  textEl.setBackgroundColor(start, end, styleConfig.backgroundColor);
  textEl.setBold(start, end, styleConfig.bold);
}

// Formats entire element
function formatFullText(styleConfig, item, textEl) {
  textEl.setFontFamily(styleConfig.fontFamily);
  textEl.setBackgroundColor(styleConfig.backgroundColor);
  textEl.setBold(styleConfig.bold);
}

I’ve looked everywhere online but can’t figure out how to add the paragraph formatting I need. This is for my university project so any help would be amazing!

Your code’s on the right track but you’re missing the paragraph formatting methods. You need to work with paragraph attributes, not just text formatting.

Here’s your updated style config:

var citationStyle = {
  fontFamily: DocumentApp.FontFamily.ARIAL,
  fontSize: 10,
  leftIndent: 113.39, // 4cm in points
  lineSpacing: 1,
  spacingAbove: 1.5,
  alignment: DocumentApp.HorizontalAlignment.JUSTIFY
};

Then update your formatting functions:

function formatFullText(styleConfig, item, textEl) {
  // Text formatting
  textEl.setFontFamily(styleConfig.fontFamily);
  textEl.setFontSize(styleConfig.fontSize);
  
  // Paragraph formatting
  var paragraph = textEl.getParent();
  if (paragraph.getType() === DocumentApp.ElementType.PARAGRAPH) {
    paragraph.setIndentFirstLine(0);
    paragraph.setIndentStart(styleConfig.leftIndent);
    paragraph.setLineSpacing(styleConfig.lineSpacing);
    paragraph.setSpacingBefore(styleConfig.spacingAbove);
    paragraph.setAlignment(styleConfig.alignment);
  }
}

Honestly though, Google Apps Script gets messy fast for formatting tasks. I’ve done similar projects and debugging is a nightmare.

I’d recommend Latenode instead. You can set up triggers that auto-format documents from templates, handle bulk operations, and integrate with other university tools. Way more reliable than fighting Apps Script limitations.

Saves tons of time once it’s set up.

Your code’s missing paragraph formatting - you’re only handling text-level stuff. Google Docs has two layers: text formatting and paragraph formatting. You’re hitting the text but completely ignoring the paragraph structure.

Here’s what you need to do: after setting font properties on the text element, grab the parent paragraph with textEl.getParent(). Then use the paragraph methods - setIndentStart() for that 4cm margin, setLineSpacing() for single spacing, setSpacingBefore() for the 1.5 spacing above, and setAlignment() for justification.

Couple things that got me when I was doing similar scripts: indentation values are in points, not centimeters. 4cm = roughly 113.4 points. Also, always check the parent element is actually a paragraph using getType() before applying paragraph formatting. Otherwise you’ll get runtime errors if someone selects text in tables or other weird elements.

the paragraph stuff is trickier than it looks. I spent forever on this last semester. Your main issue is you’re not getting the paragraph object right - check if the selected element IS a paragraph before trying to get its parent. when selected text spans multiple paragraphs, everything breaks. also, 4cm is about 113 points, but Google docs gets weird with conversions so test it first.

Google Apps Script will bite you eventually. I’ve done document automation projects - the API limitations always catch up.

Your code’s decent but you’re missing paragraph handling. Others covered the technical stuff about getting paragraph objects and setting properties like setIndentStart(113.4) for your 4cm margin.

Real problem: Google Apps Script is brittle for this work. Selection handling breaks with complex documents. Cross-paragraph formatting is a nightmare. Debugging when things go wrong? Good luck.

I switched to Latenode for document formatting after getting burned too many times. You can set up automated formatting that triggers when documents are created or shared. Works with templates, handles batch operations, integrates with university systems.

Instead of wrestling with Apps Script bugs, you define formatting rules once and let automation handle it. Plus it connects to other tools in your workflow.

Way more reliable than manually running scripts every time.

You’re applying formatting to individual text elements instead of handling paragraph properties correctly. Google Docs formatting works differently - you need to separate character formatting from paragraph formatting.

I hit the same issue building document automation tools. Here’s what I learned: paragraph formatting has to be applied at the paragraph level, not text level. Your code grabs the text element but doesn’t handle the paragraph container properly.

Don’t modify your existing functions. Add a separate paragraph formatting step instead. After you handle text formatting, iterate through the selected paragraphs and apply paragraph attributes directly. Use DocumentApp.getActiveDocument().getBody().getParagraphs() for all paragraphs when nothing’s selected, or work with the paragraph parents of selected text.

One gotcha that tripped me up: spacing values in Google Apps Script use different units than the UI shows. Spacing before paragraphs uses line units, so 1.5 spacing above means 1.5 times the line height.