Google Apps Script offers powerful capabilities for automating tasks within Google Docs. Imagine automatically generating reports, creating standardized documents, or applying consistent formatting across multiple files. This section will guide you through the essentials of programmatically creating and formatting Google Docs, saving you significant time and reducing manual effort.
The core of interacting with Google Docs in Apps Script is the DocumentApp service. This service provides access to the user's Google Docs and allows you to create, open, and manipulate them. We'll start by learning how to create a brand new document.
function createNewDocument() {
var doc = DocumentApp.create('My New Automated Document');
Logger.log('Created document: ' + doc.getUrl());
}When you run this script, a new Google Doc titled 'My New Automated Document' will be created in your Google Drive. The doc.getUrl() method is incredibly useful for quickly accessing the newly created document.
Once a document is created, you'll want to add content. Google Docs are structured with a body, which contains paragraphs, headings, lists, and other elements. The DocumentApp service provides methods to access and manipulate this body.
function addContentToDocument() {
var doc = DocumentApp.create('Document with Content');
var body = doc.getBody();
body.appendParagraph('This is the first paragraph.');
body.appendParagraph('This is a second paragraph, added automatically.');
Logger.log('Document with content created: ' + doc.getUrl());
}The appendParagraph() method is your go-to for adding new text blocks to the document. You can call it multiple times to build up your document's content.
Formatting is where Apps Script truly shines in streamlining workflows. You can control font styles, sizes, colors, alignment, and even create lists and tables. Let's explore some common formatting options.