patto_chennai
patto_chennai

Reputation: 71

Unable to get DocumentBodySection.appendImage(InlineImage) to function properly?

https://developers.google.com/apps-script/class_documentbodysection#appendImage

I basically open a document and get its DocumentBodySection, I then iterate through the elements, copy them (Element.copy()) to get a deep detached copy and then append the element to another document.

This works well for paragraph and other element types, but when it comes to inline images, I get a broken link in the resulting document.

Anyone got that to work?

Here is a snippet

function appendSection(doc, section) {
  for (i=0; i<section.getNumChildren(); i++) {
    var el = section.getChild(i);
    if (el.getType() == DocumentApp.ElementType.PARAGRAPH)
    {
      if (el.getNumChildren() != 0) {
        var el_child = el.getChild(0);
        if (el_child.getType() == DocumentApp.ElementType.INLINE_IMAGE)
        {
          doc.appendImage(el_child.asInlineImage().copy());
          Logger.log("Image");
        }
      }
      doc.appendParagraph(el.copy());
      Logger.log("Paragraph");
    }
  }     
  return doc
}

Thanks in advance.

Upvotes: 1

Views: 1251

Answers (1)

Fausto R.
Fausto R.

Reputation: 1334

I got appendImage to work for me in not the same, but similar case.

Hopefully it will do for you as well, please let me know

Adapting from your code, just add / change the Blob lines to avoid repeated inline images

  if (el_child.getType() == DocumentApp.ElementType.INLINE_IMAGE)
  {
    var blob = el_child.asInlineImage().getBlob();
    doc.appendImage(blob);
  } 

EDIT 1: as commented below, when looping through the bodySection, any INLINE_IMAGE will be embedded in a PARAGRAPH. The code below will work for any INLINE_IMAGE that is not wrapped with text. If that was the case, you need to dig deeper.

for (var elem = 0; elem < bodySection.getNumChildren(); elem++) {
          var theElem = bodySection.getChild(elem).copy();
          if (theElem.getType() == DocumentApp.ElementType.PARAGRAPH) {
            if (theElem.asParagraph().getNumChildren() != 0 && theElem.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
              var blob = theElem.asParagraph().getChild(0).asInlineImage().getBlob();
              targetDoc.appendImage(blob);
            }
            else targetDoc.appendParagraph(theElem.asParagraph());
          }
          if (theElem.getType() == DocumentApp.ElementType.LIST_ITEM) targetDoc.appendListItem(theElem.asListItem().copy());
          if (theElem.getType() == DocumentApp.ElementType.TABLE) targetDoc.appendTable(theElem.asTable());
        }

Upvotes: 2

Related Questions