无法让DocumentBodySection.appendImage(InlineImage)正常运行?

时间:2012-07-02 15:27:37

标签: google-apps-script

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

我基本上打开一个文档并获取它的DocumentBodySection,然后我遍历这些元素,复制它们(Element.copy())以获得一个深度分离的副本,然后将该元素附加到另一个文档。

这适用于段落和其他元素类型,但是当涉及到内嵌图像时,我在结果文档中得到一个断开的链接。

任何人都有这个工作吗?

这是一个片段

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
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

我得到的appendImage对我来说不一样,但情况类似。

希望它也适合你,请让我知道

根据您的代码进行调整,只需添加/更改Blob线以避免重复的内嵌图像

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

编辑1:如下所述,当循环遍历bodySection时,任何INLINE_IMAGE都将嵌入到PARAGRAPH中。以下代码适用于未包含文本的任何INLINE_IMAGE。如果是这种情况,你需要深入挖掘。

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());
        }
相关问题