Can I transfer images from Google Sheets to a Google Docs template during creation?

Hey everyone! I’m trying to figure out if it’s possible to move an image from my Google Sheet to a Google Docs template while creating a new document. I’ve got a script that pulls data from the sheet and fills in placeholders in the Doc template. But I’m stuck on how to process images.

Here’s what I’m doing now:

// Get data from the sheet
let employeeData = sheet.getRange(row, 1, 1, 13).getValues()[0];

// Create a new document
let newDocument = DocumentApp.create('Employee Record');
let docBody = newDocument.getBody();

// Replace placeholders
 docBody.replaceText('{{employeeName}}', employeeData[1]);
 docBody.replaceText('{{employeeId}}', employeeData[2]);
 docBody.replaceText('{{employeeDept}}', employeeData[3]);
// ... additional replacements ...

// How do I add the image from the sheet cell?

Any advice to embed an image from a sheet into the new document would be really appreciated!

hey tom! try enabling the Drive API and use DriveApp.getFileById() to fetch your sheet image.
then insert it into your doc. might need tweaking but it should work!

To transfer images from Google Sheets to a Google Docs template during creation, you’ll need to use the Advanced Drive Service. First, enable it in the Apps Script editor under Services. Then, modify your script to retrieve the image from Sheets and insert it into your new document.

Here’s a basic approach:

  1. Get the image blob from your sheet cell.
  2. Create a temporary file in Drive with the image.
  3. Insert the image into your new document using its file ID.
  4. Delete the temporary file.

Remember to handle potential errors, like missing images or API issues. Also, consider performance implications if you’re processing many documents with large images.

I’ve actually tackled this issue before in one of my projects. The key is using the Advanced Drive Service, as WhisperingWind mentioned. Here’s what worked for me:

  1. Enable the Advanced Drive Service in the script editor.
  2. Grab the image URL from your sheet cell.
  3. Use UrlFetchApp to get the image as a blob.
  4. Create a temporary file in Drive with DriveApp.createFile().
  5. Insert the image into your document with body.appendImage(blob).

One gotcha: make sure your image URLs are set to ‘Anyone with the link can view’ in Drive, so you don’t run into permission issues.

Also, clean up by deleting the temporary file after insertion. This helps avoid cluttering your Drive with unnecessary files.

Hope this helps, Tom! Let me know if you need further clarification.