[ad_1]

How to change the font family and font styles of various Word documents in your Google Drive with Apps Script

An organization has recently migrated its Microsoft Office Word documents to Google Drive. Migration has been easy, but imported Word documents such as Google Docs use Caliber, Microsoft Word’s default font family.

The company is looking to replace the fonts in various Google documents so that the document headings use Georgia while the body paragraphs are rendered in Droid Sans at 12 p.m.

Replace font styles in Google Docs

This example shows how to replace the font family of your Google Docs in specific sections: the titles of the headings are represented by a different font, while the tables, list items, body, and table contents have a different format.

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 Reply

Your email address will not be published. Required fields are marked *