如何使用 AppScript 将图像插入 Google 文档?

How to insert images to a Google Document using AppScript?

我有一个脚本可以在运行时创建一个文档并将其附加到一个变量。

我需要使用脚本向其中插入图像。

这是我的代码:

  var modulo = "foo";
  var nomeDoc = "bar";
  let doc =  DocumentApp.create("Validação escopo ("+ modulo +") cliente: " + nomeDoc);
  var body = doc.getBody();
  var imgPDF = body.appendImage(blob);

如何在变量中将图像作为“blob”传递:imgPDF

重要提示:图像在调用此函数的电子表格中。

2022 年 1 月 19 日,电子表格服务中添加了 2 类 用于使用内部单元格图像。 Ref 但是,在当前阶段,图像可以放入单元格中。但是,不幸的是,无法检索单元格中的图像。我认为这可能是一个错误。而且,这些 类 无法检索单元格上的图像作为 blob 和图像 URL。我认为这是规范。

所以,作为目前的解决方法,我认为在你的情况下,在当前阶段,可以使用这种方法。 Ref

在此解决方法中,可以使用 Google Apps 脚本库。 Ref 这个库可以检索单元格中的图像和单元格中的图像。

用法:

1。安装 Google Apps 脚本库。

这个库的安装方法见here

2。启用驱动器 API.

在这种情况下,使用驱动器 API。所以,please enable Drive API at Advanced Google services.

3。示例脚本。

const spreadsheetId = "###"; // Google Spreadsheet ID
const res = DocsServiceApp.openBySpreadsheetId(spreadsheetId).getSheetByName("Sheet1").getImages();
console.log(res); // You can check the retrieved images at the log.
if (res.length == 0) return;
const blob = res[0].image.blob; // Here, 1st image of Sheet1 is retrieved. Of course, you can choose the image on the sheet.

let doc = DocumentApp.create("Validação escopo (" + modulo + ") cliente: " + nomeDoc);
var body = doc.getBody();
var imgPDF = body.appendImage(blob);
  • 在这种情况下,请声明 modulonomeDoc

4。正在测试。

当上述脚本为运行时,从“Sheet1”中检索图像并将第一个图像放入创建的文档正文中。

参考文献:

  • DocsServiceApp
  • 相关话题
    • How to access new 'in-cell-image' from google apps script?