javascriptgoogle-apps-scriptgoogle-docs

Google Apps Script isn't appending paragraphs / tables and is throwing an error that document cannot be found


I am trying to build a quote generator where data is taken from a spreadsheet and put into a document. Multiple items may be chosen, so I want to put one page per spreadsheet item. Therefore I was trying to copy elements from a template document to a new document then change the text. However, no matter which method I try the paragraphs / tables are not appended, and the final message in Apps Script is "Document is missing (perhaps it was deleted, or you don't have read access?)." No other information, no line noted, nothing. I've tried using SWTICH() and IF() chains and neither work.

function test() {
  const tempDoc = DocumentApp.openById(<ID_1>).getBody();
  const newDoc = DocumentApp.openById(<ID_2>);

  let numEl = tempDoc.getNumChildren();
  let outBody = newDoc.getBody();

  console.log(outBody);

  let el, type;
  for (let j = 0; j < numEl; j++) {
    el = tempDoc.getChild(j).copy();
    type = el.getType();

    switch (type) {
      case DocumentApp.ElementType.PARAGRAPH:
        outBody.appendParagraph(el.asParagraph());
        break;
      case DocumentApp.ElementType.TABLE:
        outBody.appendTable(el.asTable());
        break;
      default:
        console.log("end");
        break;
    }
  }
}

Solution

  • It turns out that the issue was that you cannot use .getChild().copy() to move things from one document to another; that method only works to copy elements within the same document. Rather, I have to use .getParagraphs()[].copy() to copy paragraphs and .getTables()[].copy() to copy tables from one document to another.

    A very unhelpful and unintuitive error message, but it's sorted now.