javascriptgoogle-apps-scriptgoogle-docsgoogle-docs-api

Unexpected Blank Line Appearing in Google Doc Created with Apps Script


I'm working on a Google Apps Script that generates a word file based on data from a Google Spreadsheet. The script creates a Google Doc, formats it, and inserts various pieces of information. However, I'm encountering an issue where an unexpected blank line appears in the generated document after the name paragraph, regardless of the text or elements I insert or even if I comment out parts of the code related to that section.

function create() {
  var fileName = SpreadsheetApp.getActiveSpreadsheet().getName();
  var name = fileName.replace(/\.[^/.]+$/, "");
  var formattedName = "CV - " + name;

  var doc = DocumentApp.create(formattedName);
  var docBody = doc.getBody();

  // Setting document margins
  docBody.setAttributes({
    [DocumentApp.Attribute.MARGIN_TOP]: 72,
    [DocumentApp.Attribute.MARGIN_BOTTOM]: 72,
    [DocumentApp.Attribute.MARGIN_LEFT]: 72,
    [DocumentApp.Attribute.MARGIN_RIGHT]: 72
  });

  // Inserting name paragraph
  var nameParagraph = docBody.insertParagraph(0, name);
  nameParagraph.setHeading(DocumentApp.ParagraphHeading.HEADING1);

  // The issue: An unexpected blank line appears here in the document

  // Further content insertion...
}

// Additional relevant functions like createTitle(), addFormattedParagraph(), etc.

enter image description here

enter image description here


Solution

  • I think that when you create a document it always has at least one child. In this case you can probably use something like:

    body.getChild(1).asParagraph().removeFromParent()
    

    In the first example it maybe body.getChild(0)