Google Apps脚本 - appendParagraph与图片

时间:2015-09-26 10:45:00

标签: google-apps-script

我有一个插件,可以将“模板”文档文件中的内容复制到当前打开的Doc文档中。

在源文档正文中使用内嵌图像时,会复制文本,但UI会显示“重新连接”消息。灰色图像占位符区域显示为加载。关闭文档并重新打开Goog​​le云端硬盘错误后会显示。

奇怪的是,如果我将图像放在标题中的源文档中,则所有内容都会正确附加。

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

}

我已经尝试了这个Unable to get DocumentBodySection.appendImage(InlineImage) to function properly?但是带有内嵌图像的段落没有子节点,因此永远不会执行if语句。

我还注意到复制/追加并不总是使用源文档元素的字体系列...有时它会这样做,有时候不会。

1 个答案:

答案 0 :(得分:1)

我认为这应该注意正确添加内嵌图像:

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

因此,当它没有孩子时,else语句应该处理它。

对于复制/追加,您可以编写一个onEdit()函数,该函数将使用setAttributes方法处理所有格式。以下是一个示例:

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

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

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

希望这有帮助。