谷歌脚本:如何使用文档模板显示图像而不是超链接



我有一个G-Sheet,其中有3000行数据,一列中有指向图像的链接。我可以使用body.replaceText来填写我创建的谷歌文档模板。问题是它只是简单地拉超链接。

不显示超链接,您将如何显示实际图像?

感谢您抽出时间!

function newGoogleDoc() {
const googleDocTemplate = DriveApp.getFileById('XXXXX');
const destinationFolder = DriveApp.getFolderById('XXXXX')
const sheet = SpreadsheetApp
.getActiveSpreadsheet()
const rows = sheet.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
if (row[15]) return;
const copy = googleDocTemplate.makeCopy(`${row[1]}, ${row[0]} Employee Details` , destinationFolder)
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();
const friendlyDate = new Date(row[12]).toLocaleDateString();
body.replaceText('{{Scope}}', row[0]);
body.replaceText('{{Block}}', row[1]);
body.replaceText('{{Line Item}}', row[2]);
body.replaceText('{{Date}}', friendlyDate);
body.replaceText('{{User}}', row[13]);
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index + 1, 15).setValue(url)
})
}

如果图像的占位符是自己的段落,而不是包含其他内容的容器元素的一部分,则可以执行以下操作:

  • 使用findText(searchPattern(查找占位符
  • 通过UrlFetchApp.fetch(URL(和getBlob((从图像URL中获取Blob
  • 获取包含占位符的容器元素,并使用insertInlineImage将检索到的图像插入到该元素的开头

例如,如果图像的URL在列A中(因此图像应替换{{Scope}}(,则可以替换此行:

body.replaceText('{{Scope}}', row[0]);

有了这个:

const rangeElement = body.findText('{{Scope}}');
const imageBlob = UrlFetchApp.fetch(row[0]).getBlob();
if (rangeElement) {
const element = rangeElement.getElement();
element.asText().setText("");
const image = element.getParent().asParagraph().insertInlineImage(0, imageBlob);
}

重要提示:

这将删除占位符所在段落中的所有其他内容。您也可以在段落之前或之后附加图像,但不能在占位符所在的位置。请参阅此相关问题。

其他问题:

  • 与其在每次迭代中检查是否为index === 0,我建议要么获取不带标头的范围(.getRange(2,1, sheet.getLastRow() - 1, sheet.getLastColumn())(,要么从外部数组中删除标头数组(rows.shift()(。不过,在这种情况下,您应该小心修改循环中对index的所有其他提及,因为它将引用的行将是不同的
  • 在循环中调用setValue不是最佳做法。我建议将数据推送到数组中(例如urls.push([url])(,并在循环结束后立即写入这些值(使用setValues((例如sheet.getRange(1,15,urls.length).setValues(urls)(

您需要将图像url转换为blob,然后定义在文档中输入它的位置。替换文本仅用文本替换文本。

改编自的解决方案https://www.labnol.org/code/20078-insert-image-in-google-document

function webImage() {
//continuing from your code
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();

// using example image url, not sure which row has your urls
var image = 'www.imageurl.com/image.jpg';
var blob = UrlFetchApp.fetch(image).getBlob();

// find position, not sure what you are using in the doc, used text PLACEHOLDER as an example
var position = body.findText('PLACEHOLDER').getElement()
var offset = body.getChildIndex(position.getParent())

// insert image
body.insertImage(offset +1,blob)
// remove placeholder text
position.removeFromParent()
}

另一个解决方案:通过谷歌应用程序脚本将图像添加到谷歌文档

最新更新