Create google doc, insert text with specific paragraph styles

1,176 views
Skip to first unread message

João Silva

unread,
Jan 31, 2022, 11:02:11 AM1/31/22
to Google Apps Script Community
Hello.

I'm trying to create a script that will help me generate a new Google Doc and populate it with some text. That text should be formatted with different paragraph styles. I would use this to create a google doc where I keep notes about my students and their projects. My usual format is something like:

Class name (formatted with Heading 1)
Student 1 name (Heading 2)
Project 1 (Heading 3)
Project 2 ( Heading 3)
Final Project (Heading 3)
...
Student N name (Heading 2)

And so on.

Looking at the script reference, I can't find how to do this. The best I found was how to style text by setting each property - https://developers.google.com/apps-script/advanced/docs#insert_and_style_text - which is not really what I want. 

Is there a way to achieve this? Thank you.

Edward Ulle

unread,
Jan 31, 2022, 11:28:46 AM1/31/22
to Google Apps Script Community
Try this.

function onOpen() {
  var menu = DocumentApp.getUi().createMenu("My Menu");
  menu.addItem("Test","test");
  menu.addToUi();
}

function test() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var body = doc.getBody();
    var para = body.appendParagraph("Class name");
    para.setHeading(DocumentApp.ParagraphHeading.HEADING1);
    para = body.appendParagraph("Type to insert class");
    para = body.appendParagraph("Student 1");
    para.setHeading(DocumentApp.ParagraphHeading.HEADING2);
    para = body.appendParagraph("Type to insert student");
    para = body.appendParagraph("Project 1");
    para.setHeading(DocumentApp.ParagraphHeading.HEADING3);
    para = body.appendParagraph("Type to insert student");
  }
  catch(err) {
    DocumentApp.getUi().alert(err);
  }
}

Reply all
Reply to author
Forward
0 new messages