Home > other >  Google Apps Script - setting Line spacing and Heading1 in a table cell
Google Apps Script - setting Line spacing and Heading1 in a table cell

Time:09-27

Thanks to @Tanaike for providing answers to my previous question. I have 2 other issues.

1 - When set spacing is 1 but when check in Google Doc, the spacing was 1.15.

heading1Style[DocumentApp.Attribute.LINE_SPACING] = 1;

2 - I tried to set DocumentApp.ParagraphHeading.Heading1 to the following but it does not works.

tableRow1.getCell(0, 1).editAsText().setAttributes(heading1Style);

The following is the whole code.

function insertHeading1() {
  var heading1Style = {};
  heading1Style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
  heading1Style[DocumentApp.Attribute.FONT_SIZE] = 18;
  heading1Style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
  heading1Style[DocumentApp.Attribute.LINE_SPACING] = 1;
  heading1Style[DocumentApp.Attribute.BOLD] = true;

  var cells = [
    [' ', 'HEADING 1, CALIBRI, 18PT, BOLD, LEFT ALIGNED, ALL CAPS, SINGLE SPACING, NO SPACE BEFORE AND AFTER PARAGRAPH'],
  ];

  var tableRow1 = body.appendTable(cells);
  tableRow1.setColumnWidth(0, 10);
  tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69');
  tableRow1.getCell(0, 1).editAsText().setAttributes(heading1Style);
}

CodePudding user response:

  • You are setting the declared style attributes to a TableCell object. However you cannot change Line Spacing of a TableCell object directly in Google Docs.
  • What you can do instead is add a Paragragph object on that cell and then modify the lineSpacing. To do that, you can call the method insertParagraph(childIndex, text) of the TableCell object of the second table cell.

I've slightly modified the sample code:


function insertHeading1() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();

  var heading1Style = {};
  heading1Style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
  heading1Style[DocumentApp.Attribute.FONT_SIZE] = 18;
  heading1Style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
  // heading1Style[DocumentApp.Attribute.LINE_SPACING] = 1;
  heading1Style[DocumentApp.Attribute.BOLD] = true;

  var cells = [
    ['', ''],
  ];

  var tableRow1 = body.appendTable(cells);
  tableRow1.setColumnWidth(0, 10);
  tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69');
  tableRow1.getCell(0, 1).setAttributes(heading1Style);
  tableRow1.getCell(0, 1)
      .insertParagraph(0, 'HEADING 1, CALIBRI, 18PT, BOLD, LEFT ALIGNED, ALL CAPS, SINGLE SPACING, NO SPACE BEFORE AND AFTER PARAGRAPH')
      .setLineSpacing(1);
  tableRow1.getCell(0, 1).removeChild(tableRow1.getCell(0, 1).getChild(1)); // deletes the additional paragraph created by appendTable()
}
  • Related