How to Change the Font in your Google Documents with Apps Script

Hey, friends today I will teach you How to change the font family and font styles of multiple Word documents in your Google Drive with Apps Script. A company recently moved its Word Documents from Microsoft Office to Google Drive. The migration went smoothly, but the Word documents imported as Google Docs use Calibri, Microsoft Word’s default font family. so let get started with today Code snippets. Getting different problems is altogether gives a very different experience. today the Code snippets I am going to share with you is How to change the font family and font styles of multiple Word documents in your Google Drive with Apps Script.

How to Change the Font in your Google Documents with Apps Script

The company intends to replace the fonts in several Google Docs so that the document headings are rendered in Georgia while the body paragraphs are rendered in Droid Sans at 12 pt.

You might also like our trending code snippets

Replace Font Styles in Google Docs

This example shows how to change the font family of specific sections of your Google Documents – the heading titles are rendered in a different font, while the tables, list items, body, and table of contents are formatted with a different font.

const updateFontFamily = () => {
  const document = DocumentApp.getActiveDocument();

  const headingStyles = {
    [DocumentApp.Attribute.FONT_FAMILY]: "Georgia",
    [DocumentApp.Attribute.FONT_SIZE]: 14,
  };

  const normalParagraphStyles = {
    [DocumentApp.Attribute.FONT_FAMILY]: "Droid Sans",
    [DocumentApp.Attribute.FONT_SIZE]: 12,
  };

  const body = document.getBody();

  [...Array(body.getNumChildren())].map((_, index) => {
    const child = body.getChild(index);
    const childType = child.getType();
    if (childType === DocumentApp.ElementType.PARAGRAPH) {
      if (
        child.asParagraph().getHeading() === DocumentApp.ParagraphHeading.NORMAL
      ) {
        child.setAttributes(normalParagraphStyles);
      } else {
        child.setAttributes(headingStyles);
      }
    } else if (childType === DocumentApp.ElementType.TABLE) {
      child.setAttributes(normalParagraphStyles);
    } else if (childType === DocumentApp.ElementType.TABLE_OF_CONTENTS) {
      child.setAttributes(normalParagraphStyles);
    } else if (childType === DocumentApp.ElementType.LIST_ITEM) {
      child.setAttributes(normalParagraphStyles);
    }
  });

  document.saveAndClose();
};

Leave a Comment