1
votes

I have an add-on that copies content from "template" Docs files into the current open Doc document.

When inline images are used in the body of the source Doc, the text is copied but the UI shows a "reconnecting" message. A greyed out image placeholder area is being displayed as loading. After closing the document and re-opening a Google Drive error is displayed.

Oddly enough if I place the image in the source Doc in the header, everything is appended correctly.

var targetBody = targetDoc.getBody();

  for( var j = 0; j < totalElementsBody; ++j ) {
    var element = templateBody.getChild(j).copy();
    var type = element.getType();
    if (type == DocumentApp.ElementType.PARAGRAPH) {
      targetBody.appendParagraph(element);
    }
    else if( type == DocumentApp.ElementType.TABLE){
      targetBody.appendTable(element);
    }
    else if( type == DocumentApp.ElementType.LIST_ITEM){
      targetBody.appendListItem(element);
    }
    else if( type == DocumentApp.ElementType.INLINE_IMAGE) {
      var image = element.asInlineImage().getBlob();
      targetBody.appendImage(image);
    }
    else if( type == DocumentApp.ElementType.HORIZONTAL_RULE) {
      targetBody.appendHorizontalRule();
    }
    else if( type == DocumentApp.ElementType.PAGE_BREAK) {
      targetBody.appendPageBreak();
    }

}

I have tried this Unable to get DocumentBodySection.appendImage(InlineImage) to function properly? but the paragraph with the inline image has no children, so the if-statement is never executed.

I also noticed that copying/appending does not always use the font-family of the source document elements... sometimes it does, sometimes not.

1

1 Answers

1
votes

I believe this should take care of adding the image inline properly:

   if (type == DocumentApp.ElementType.PARAGRAPH) 
   {
      if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) 
      {
        var blob = element.asParagraph().getChild(0).asInlineImage().getBlob();
        doc.appendImage(blob);
      }
      else doc.appendParagraph(element.asParagraph());
    }

hence, when it doesn't have children, the else statement should take care of it.

For copying/appending, you can write an onEdit() function that would take care of all the formatting using the setAttributes method. Below is a sample:

function onEdit()
{
  var doc = DocumentApp.getActiveDocument();

  var style = {};
  style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
  style[DocumentApp.Attribute.FONT_SIZE] = 18;

  doc.getBody().setAttributes(style);
}

Hope this helps.