How to Use Conditional Logic in Google Documents

Conditional content allows you to customize your Google Docs template and generate different versions of the same document based on the user’s answers. In this tutorial, I’ll show you how to use conditional content in Google Docs using Document Studio, a Google add-on that automates document creation.

If you are new here, please follow this step-by-step guide on how to generate documents from data in Google Sheets and Google Forms responses.

Conditionally Display Content

Job Candidates in Google Sheets

Let’s say you are a recruiter who wants to use a Google Docs template to send out job offer letters to candidates. You want to include specific information in the offer letter based on the candidate’s job title and location.

The conditional statements that we would like to include in the document template are:

  1. Your office is located in San Francisco. Your offer letter should include a paragraph offering relocation benefits only to candidates who are located outside SF.
  2. If the candidate is offered an Associate position, they are eligible for basic benefits.
  3. If the candidate is hired for a senior position, like Manager or Director, they are entitled to additional benefits like 401(k) retirement plan.

Define the conditional sections

Create a new Google Docs document and create a job offer letter template. Include sections for the candidate’s name, job title, location, salary, and benefits package.

Conditional Logic in Google Docs

Use the <<if>> and <<endif>> expressions to define the conditional sections in your template. For example, you might use the following expressions to show or hide the relocation package section based on the candidate’s location:

<<If: ({{Location}} != 'San Francisco')>>
We are pleased to offer you a relocation package to assist with your move from {{Location}} to our main office.
<<EndIf>>

Similarly, you can wrap the benefits paragraph with the <<if>> and <<endif>> expressions to show or hide the benefits package section based on the candidate’s job title:

<<If: OR (({{Job Title}} == 'Manager'), ({{Job Title}} == 'Director'))>>
As {{Job Title}}, you will be eligible for our comprehensive benefits package, which includes health, dental, and vision insurance, a 401(k) retirement plan, and more.
<<EndIf>>

You may also use the ~ contains operator in place of == equals operator for partial matches. For instance, {{Job Title}} ~ 'Manager' will match Sales Manager, Senior Manager, Manager and so on.

Here’s how the final job offer letter template looks like.

https://www.youtube.com/watch?v=UbMlmckpZDg

In addition to document templates, you can also add conditional text in email templates with the help of scriptlets.

Things to know:

  1. You may not nest IF statements inside each other.
  2. You can use the OR, AND or NOR operator to combine multiple conditions.
  3. If you have a table in your document that should be displayed conditionally, you should put the wrapping <<if>> and <<endif>> tags outside the table.
  4. It is currently not possible to hide or show specific rows or columns of a table based on the user’s answers.

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

An organization recently migrated their Word Documents from Microsoft Office to Google Drive. The migration has been smooth but the Word documents imported as Google Docs are using Calibri, the default font family of Microsoft Word.

The company is looking to replace the fonts in multiple Google Documents such that the document headings using Georgia while the body paragraphs are rendered in Droid Sans at 12 pt.

Replace Font Styles in Google Docs

This example show how to replace the font family of your Google Documents of specific sections - the heading titles are rendered in a different font while the tables, list items, body and table of contents are formatted with a separate 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();
};

How to Replace Text and Hyperlinks in Google Documents with Apps Script

The company’s handbook is written in Google Docs. The document spans several pages and now the writer has been asked to create links such that all mentions of the company name in the document are linking to the company’s official website.

It can be a time consuming task but with Google Apps Script, specific words in a document can be hyperlinked in bulk in one click.

This example show how to search and replace all occurrences of a text phrase, the company name in this case, and add links to a specific website.

const addLinks = () => {
  const searchPhrase = "Digital Inspiration";
  const hyperlink = "https://digitalinspiration.com/";

  const document = DocumentApp.getActiveDocument();
  const body = document.getBody();
  let search = null;

  while ((search = body.findText(searchPhrase, search))) {
    const searchElement = search.getElement();
    const startIndex = search.getStartOffset();
    const endIndex = search.getEndOffsetInclusive();
    searchElement.asText().setLinkUrl(startIndex, endIndex, hyperlink);
  }

  document.saveAndClose();
};

For the next iteration of the handbook, the company’s name has changed but the website domain is the same. The writer is required to change every instance of the company’s name in the document but the underlying hyperlink should not be modified..

const changeText = () => {
  const searchText = "Blue Widgets Inc.";
  const replaceText = "Orange Inc.";

  const document = DocumentApp.getActiveDocument();
  const body = document.getBody();
  let search = null;

  while ((search = body.findText(searchText, search))) {
    const searchElement = search.getElement();
    const startIndex = search.getStartOffset();
    const endIndex = search.getEndOffsetInclusive();

    const textElement = searchElement.asText();
    const existingLink = textElement.getLinkUrl(startIndex);
    textElement.deleteText(startIndex, endIndex);
    textElement.insertText(startIndex, replaceText);
    textElement.setLinkUrl(
      startIndex,
      startIndex + replaceText.length - 1,
      existingLink
    );
  }

  document.saveAndClose();
};

The next Apps Script snippets shows how to change all instance of the company name and also replace the site URL with another domain name.

const changeTextWithUrl = () => {
  const searchText = "Blue Widgets Inc.";
  const replaceText = "Orange Inc.";
  const replaceUrl = "https://digitalinspiration.com/";

  const document = DocumentApp.getActiveDocument();
  const body = document.getBody();
  let search = null;

  while ((search = body.findText(searchText, search))) {
    const searchElement = search.getElement();
    const startIndex = search.getStartOffset();
    const endIndex = search.getEndOffsetInclusive();

    const textElement = searchElement.asText();
    textElement.deleteText(startIndex, endIndex);
    textElement.insertText(startIndex, replaceText);
    textElement.setLinkUrl(
      startIndex,
      startIndex + replaceText.length - 1,
      replaceUrl
    );
  }

  document.saveAndClose();
};

How to Add a Watermark in Google Documents

Microsoft Word includes a useful “Insert Watermark” feature to help you easily add your brand’s logo image or a text stamp that fades behind the content of every page in the document. A company’s policy may require employees to add watermarks to indicate if any document is in draft stage or if the document is confidential and not meant for external distribution.

Microsoft Word Watermark

Insert Watermarks in Google Docs

Unlike Microsoft Word, there’s no built-in support for Watermarks in Google Docs but there’s a simple workaround - create a faded image with the text of your watermark and place that image behind the text of your document pages. Here’s how:

1. Create the watermark stamp

Launch MS Paint on your computer and create a simple watermark image in landscape mode with dark gray text. Please use a bold font like Impact with large font size as the large image can always be resized inside Google Docs but not vice-versa.

I’ve also added some ready-to-use image stamps on Canva and Imgur.

Upload Watermark Image

2. Upload Watermark to Google Docs

Inside Google Docs, go to the Insert menu, choose the Image submenu and select Upload from Computer. Upload the watermark image that you saved in the previous step to Google Docs.

3. Open Image Options

Right-click the uploaded image inside Google Docs and choose Image Options from the contextual menu.

Watermark Diagonal Image

4. Change Rotation

Expand the Image Options sidebar and, under the Size & Rotation section, set the angle to around 320° to make the watermark diagonal.

5. Send the Image Behind Text

  • Under the text wrapping section, choose Behind Text to send the watermark image behind the content of your document.
  • Under Position, choose the Fixed position option with the layout set as Center. This will position your watermark image right in the center of the page.
  • Under the Adjustments section, set the transparency level to around 80% to fade the watermark image in the background.

The Watermark Effect in Documents

Here’s how the final watermark effect will look like in your Google Document.

Watermark in Document

Tip: You can use Document Studio to generate PDF files from Google Forms and the watermarks would be also show up in your PDF document.

How to Add QR Codes in Emails and Google Documents

With Document Studio, you can create employee badges, event tickets, school tags and other types of documents that contain QR Code images.

To get started, go to your source spreadsheet and create a column that will the QR Code. Give it a title, say QR Code Image, and add a formula QRCODE in the first empty cell of that column as shown below.

qrcode.png

This will add the QR Code image link to all the cells of your spreadsheet where the source cell is not empty.

Add QR Codes in Google Documents

Click anywhere in the Google document where you wish to insert the QR Code and add the variable field {{QR Code Image}} - the merge process will get the QR code image link from the source sheet and replace it with an image in the generated document.

google-document-qr-code.png

Add QR Codes in Google Sheets

To add QR Codes in Google Spreadsheet, we use the IMAGE function with the first parameter as the variable field that contains the QR Code image link inside double quotes.

=IMAGE("{{QR Code Image}}", 4, 100, 100)

Remember to merge a few adjacent cells else the QR code image won’t be visible in the generated document.

spreadsheet-qr-code.png

Add QR Codes in Google Slide Presentations

In the case of Google Slides, add a new text box and type the QR code variable field inside the text box surrounded by double curly braces.

You should also vertically align the text to the top of the enclosed box so that the entire QR code image is visible.

google-slide-qrcode.png

Add QR Codes in Email Notifications

To add QR Code images in your email templates, add the HTML <img> tag with source set to the variable field that contains the QR Code.

<img src="{{QR Code Image}}" alt="QR Code" />

email-qr-code.png