插入图像插入到指定位置(Insert image into a specified location

2019-06-25 18:54发布

我有一个谷歌的Apps脚本,通过调用body.replaceText替换占位符与一些文本模板文件的副本(“TEXTA”,“TEXTB”);.

现在,我希望把它扩大到包含图像。 有谁知道知道如何做到这一点?

谢谢你,安德烈

编辑:只是为了说清楚我的脚本做什么。 我有一个电子表格创建一个谷歌的形式。 我创建了当表单提交时运行,遍历窗体对应一个表,发现未处理的行,从对应的单元格取值并把它们放在一个谷歌文档的副本的脚本。 在谷歌的形式某些字段是多行文本字段,这就是“\ r \ R”从何而来。

这里有一个解决办法,我到现在为止,没有优雅的拿出,但到目前为止的工作原理:

// replace <IMG src="URL"> with the image fetched from URL
function processIMG_(Doc) {

  var totalElements = Doc.getNumChildren();

  for( var j = 0; j < totalElements; ++j ) {

    var element = Doc.getChild(j);
    var type = element.getType();

    if (type =='PARAGRAPH'){
      var par_text = element.getText();

      var start = par_text.search(new RegExp('<IMG'));
      var end = par_text.search(new RegExp('>'));
      if (start==-1)
        continue;

      // Retrieve an image from the web.
      var url = getURL_(par_text.substring(start,end));
      if(url==null)
        continue;

      // Before image
      var substr = par_text.substring(0,start);
      var new_par = Doc.insertParagraph(++j, substr);

      // Insert image
      var resp = UrlFetchApp.fetch(url);
      new_par.appendInlineImage(resp.getBlob());

      // After image
      var substr = par_text.substring(end+1);
      Doc.insertParagraph(++j, substr);

      element.removeFromParent();
      j -= 2; // one - for latter increment; another one - for increment in for-loop
      totalElements = Doc.getNumChildren();      
    }      
  }
}

Answer 1:

下面是在支持(大约)你想要的一段代码。

(可能有其他的方法来做到这一点,它肯定需要一些改进,但总的想法是有)

我已选择使用“###”在doc来标记该图像将被插入的地方,该图像必须在你的谷歌驱动器(或在更精确地‘某些’谷歌驱动器)。下面的代码使用一个文件我共享和图像我分享过,所以你可以尝试一下。这里是链接到文档 ,不要忘记删除图像和测试(如果有的话有人您之前运行代码之前,把###的地方;-)

function analyze() { // just a name, I used it to analyse docs
  var Doc = DocumentApp.openById('1INkRIviwdjMC-PVT9io5LpiiLW8VwwIfgbq2E4xvKEo');
  var image = DocsList.getFileById('0B3qSFd3iikE3cF8tSTI4bWxFMGM')
    var totalElements = Doc.getNumChildren();
    var el=[]
    for( var j = 0; j < totalElements; ++j ) {
      var element = Doc.getChild(j);
      var type = element.getType();
Logger.log(j+" : "+type);// to see doc's content
       if (type =='PARAGRAPH'){
       el[j]=element.getText()
       if(el[j]=='###'){element.removeFromParent();// remove the ###
         Doc.insertImage(j, image);// 'image' is the image file as blob 
         }
       }
    }
}

编辑:此脚本工作的###字符串中必须是唯一的款,没有其他字符前也不后......记住,每次一个强制使用输入文档新行创建一个新的段落。



文章来源: Insert image into a specified location