从Apps脚本中的URL调用图像 [英] call an image from URL in Apps Script
问题描述
我编写了一个调用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:
- 使用文档正文,找到文本
通过 findText(searchPattern) #Photo#
并通过 getElement(). - 检索到此元素后,可以删除文本(
#Photo#
),因为即使文本为空字符串,元素本身也将存在.您可以为此使用 setText(") - 通过 UrlFetchApp.fetch(url)和 getBlob().
- 获取检索到的元素的父级,该父级是
#Photo#
的一部分,并使用
- 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
}
注意:
- 我假设您的问题只是关于将图像插入到文档中,而不是关于填充电子表格,检索图像URL等之前的步骤.
- 此示例引用了绑定到Google文档的脚本(因此,该脚本使用的是 openById(id)或 openByUrl(url).
- I'm assuming that your question was only about inserting the image to the Document, not about the previous steps of populating the spreadsheet, retrieving the image URL, etc.
- This sample refers to a script that is bound to the Google Doc (hence, it's using getActiveDocument() to retrieve the Doc). If that's not the case, you should retrieve the document via openById(id) or openByUrl(url).
Notes:
这篇关于从Apps脚本中的URL调用图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!