从Apps脚本中的URL调用图像 [英] call an image from URL in Apps Script

查看:38
本文介绍了从Apps脚本中的URL调用图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个调用Google文档的程序,该文档中有一个名为#Name#的变量,该变量被存储在SpreadSheet中的名称代替.

I programmed one that calls a Google Doc and in said Doc there is a variable called #Name# this is replaced by the name that is stored in a SpreadSheet.

我的问题是,我想向该文档添加一个名为#Photo#的变量,并将其替换为存储在Drive URL中的照片,并且此URL位于SpreadSheet中.

My question is that to that Doc I want to add a variable called # Photo # and it is replaced by the photo stored in a Drive URL and this URL is in a SpreadSheet

如何调用电子表格中的URL,并能够替换字段#photo#

How can I call that URL that is in Spreadsheet and be able to replace the field #photo#

名称与该功能配合得很好

With the name it does well with the function

body.replaceText('#name#',名称);

但是有了图片,我不知道该怎么称呼

but with the image I don't know what to call it

推荐答案

由于 #Photo#是其自身的一个段落,因此您可以执行以下操作:

Since #Photo# is a paragraph of its own, you can do the following:

  • Using the Document Body, find the text #Photo# via findText(searchPattern) and get the Element that corresponds to this text via getElement().
  • Once you have retrieved this element, you can remove the text (#Photo#), since the element itself will exist even if the text is an empty string. You can use setText("") for that.
  • Get the Blob from the image URL via UrlFetchApp.fetch(url) and getBlob().
  • Get the retrieved element's parent, which is the paragraph #Photo# was part of, and use insertInlineImage to insert the retrieved image to the beginning of this paragraph.
function replaceTextWithImage() {
  var body = DocumentApp.getActiveDocument().getBody(); // Get current document's body
  var element = body.findText("#Photo#").getElement(); // Get element of #Photo#
  element.asText().setText(""); // Remove #Photo# placeholder
  var url = "YOUR_IMAGE_URL"; // Change this accordingly
  var blob = UrlFetchApp.fetch(url).getBlob(); // Get blob from image URL
  var image = element.getParent().asParagraph().insertInlineImage(0, blob); // Insert image
}

注意:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆