Home > Mobile >  How to insert images to a Google Document using AppScript?
How to insert images to a Google Document using AppScript?

Time:03-16

I have a script that creates a document during runtime and attach it to a variable.

I need to insert images to it using a script.

Here is my code:

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

How do i pass an image as "blob" inside the variable: imgPDF?

Important: The image is in the Spreadsheet that calls this function.

CodePudding user response:

On January 19, 2022, 2 Classes for using the inner cell image were added to the Spreadsheet service. Ref But, in the current stage, the image can be put into a cell. But, unfortunately, the image in the cell cannot be retrieved. I think that this might be a bug. And also, these Classes cannot retrieve the images on a cell as the blob and the image URL. I think that this is the specification.

So, as the current workaround, I thought that in your situation, in the current stage, this method can be used. Ref

In this workaround, a Google Apps Script library might be able to be used. Ref This library can retrieve both the image in a cell and the image on a cell.

Usage:

1. Install Google Apps Script library.

You can see the method for installing this library at here.

2. Enable Drive API.

In this case, Drive API is used. So, please enable Drive API at Advanced Google services.

3. Sample script.

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);
  • In this case, please declare modulo and nomeDoc.

4. Testing.

When the above script is run, the images are retrieved from "Sheet1" and put the 1st image to the created Document body.

References:

  • Related