call an image from URL in Apps Script

霸气de小男生 提交于 2021-01-27 22:56:46

问题


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.

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

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#', name);

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


回答1:


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.

Code sample:

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
}

Notes:

  • 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).


来源:https://stackoverflow.com/questions/62601443/call-an-image-from-url-in-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!