Mail merge: can't append images from template

2019-03-04 07:46发布

问题:

I'm trying to create a mail merge function to create a document based on a simple template. I tried to use the following function to copy the template elements but I'm having problems with the (inline) images, they appear always as PARAGRAPH and not INLINE_IMAGE and the following icon appears instead of the images:

Here's the code:

function appendToDoc(src, dst) {
  // iterate accross the elements in the source adding to the destination
  for (var i = 0; i < src.getNumChildren(); i++) {
    appendElementToDoc(dst, src.getChild(i));
  }
}

function appendElementToDoc(doc, object)
{
    var element = object.copy();
    var type = object.getType();

    if (type == DocumentApp.ElementType.PARAGRAPH) {
        doc.appendParagraph(element);
    } else if (type == DocumentApp.ElementType.TABLE) {
      doc.appendTable(element);
    } else if (type== DocumentApp.ElementType.INLINE_IMAGE) { // This is never called :(
       var blob = element.asInlineImage().getBlob();
       doc.appendImage(blob); 
    }
}

Any ideas on how to solve this? Thanks in advance!

回答1:

As per my knowledge, inline images are included in a paragraph so we have to check for Image type in the Paragraph.

So the code for checking that would be this way:

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());
    }

Hope that helps!