0
votes

My Question: How do you set text to be a title or subtitle in a Google Doc using Google Apps Script? (see a visual example below)

In Google Apps Script documentation on formatting paragraphs they show the different types of ParagraphHeadings in the ParagraphHeading class and then there's the Attribute class which can be assigned to a paragraph which has some styling attributes. However, neither of these has a way to set any text as a title or a subtitle in the document. How is that accomplished?

I'm looking for something like this:

var doc = DocumentApp.getActiveDocument();

// Append a paragraph, with title.
var par1 = doc.appendParagraph("Title");
par1.setHeading(DocumentApp.ParagraphHeading.TITLE);

// Append a paragraph, with subtitle.
var par2 = doc.appendParagraph("SubTitle");
par2.setHeading(DocumentApp.ParagraphHeading.SUBTITLE);

// Append a paragraph, with heading 1.
var par3 = doc.appendParagraph("Heading 1");
par3.setHeading(DocumentApp.ParagraphHeading.HEADING1);

Here's what I mean:

Headings

3
What do you mean by title and sub title? Which part of the Google Docs UI are you referring to? - Eric Koleda

3 Answers

1
votes

I see what you mean...I think this is one of those features in appscript where there just really isn't an explanation.....it sounds like you might have to just use plain old fontstyle, fontsize, fontcolor etc to try to emulate it.

0
votes

The example script you get if you choose "Create script for... Document" doesn't use setHeading() at all, instead it explicitly manipulates the WYSIWYG attributes. (I hate when people do that in documents, and I'm only slightly less annoyed by it in script, but that's a topic for another day!)

Example, lifted directly from that sample script, including bad grammar:

function createDocument() {
  var title = 'Script Center Report';
  var summaryContents = 'This reports addresses...';
  var overviewContents = 'We undertook this project because...';
  var dataContents = 'We collected three samples of data...';

  var doc = DocumentApp.create(title);
  var footer = doc.getFooter();

  var reportTitle = doc.appendParagraph(title);
  reportTitle.setFontFamily(DocumentApp.FontFamily.ARIAL);
  reportTitle.setFontSize(24);
  reportTitle.setForegroundColor('#4A86E8');
  reportTitle.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
  ...

That's just a work-around - if you haven't done so already, you should create an issue report against apps-script to ensure all "Paragraph Types" are available to scripts.

0
votes

Unfortunately DocumentApp doesn't currently provide access to those paragraph styles. Please file a feature request on the issue tracker to have them added.