You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Google Apps Script将Drive图片插入Google文档(表单联动)

问题:Google Apps Script无法插入图片到Google文档,仅替换为URL

我通过Google表单收集数据至Google表格,其中包含Google Drive中的图片路径。编写了Google Apps Script自动填充文档模板,但目前只能将{{image}}占位符替换为图片URL,无法插入实际图片。尝试过insertImage方法但未成功,以下是我的代码:

// @ts-nocheck
function autoFillGoogleDocFromForm(e) {
  
  //e.values is an array of form values
  var timestamp = e.values[0];
  var email = e.values[1];
  var who = e.values[2];
  var employeeorcon = e.values[3];
  var location = e.values[4];
  var roomorarea = e.values[5];
  var type = e.values[6];
  var dateofworks = e.values[7];  
  var imageofcompletedcon = e.values[8];
  var checkedoffintext = e.values[9];
  var checkname = e.values[10];
  var checkco = e.values[11];
  var checkeddate = e.values[12];
 

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById("1WcYKvsRFbKK73J-ep66mR9drZyrkWap-x30rO-kVUcM"); 
  
  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById("1MeU3-N3BMqOPvoaSGr2XassibR2XajdN")
  var copy = file.makeCopy(roomorarea + '_' + timestamp, folder); 
  
  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId()); 
  
  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody(); 
  
  //Then we call all of our replaceText methods
  body.replaceText('{{location}}', location); 
  body.replaceText('{{room}}', roomorarea);   
  body.replaceText('{{completedby}}', who); 
  body.replaceText('{{checkedby}}', checkname); 
  body.replaceText('{{checkeddate}}', checkeddate);  
  body.replaceText('{{insdate}}', dateofworks); 
  body.replaceText('{{Empcon}}', employeeorcon);  
  body.replaceText('{{Type}}', type); 
  body.replaceText('{{image}}', imageofcompletedcon); 
  body.replaceText('{{methchk}}', checkedoffintext);  
  body.replaceText('{{checker}}', checkname); 
  body.replaceText('{{cocheck}}', checkco);   
  body.replaceText('{{datecheck}}', checkeddate); 
  
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose(); 
}

解决方案

核心问题是直接用replaceText将占位符替换为URL,而非插入图片对象。需要先定位占位符位置,删除文本后插入Drive中的图片,具体修改如下:

  1. 移除原有的图片URL替换代码:删除body.replaceText('{{image}}', imageofcompletedcon);这一行
  2. 添加图片插入逻辑:在其他replaceText之后加入以下代码:
// 处理图片插入
var imagePlaceholder = '{{image}}';
var searchResult = body.findText(imagePlaceholder);

if (searchResult) {
  // 获取占位符的位置信息
  var element = searchResult.getElement();
  var start = searchResult.getStartOffset();
  var end = searchResult.getEndOffsetInclusive();
  var parent = element.getParent();
  
  // 删除占位符文本
  parent.deleteText(start, end);
  
  // 从Drive链接中提取文件ID(适配标准Drive链接格式:https://drive.google.com/file/d/[ID]/...)
  var imageIdMatch = imageofcompletedcon.match(/d\/([a-zA-Z0-9-_]+)\//);
  if (imageIdMatch) {
    var imageFileId = imageIdMatch[1];
    try {
      // 获取图片文件
      var imageFile = DriveApp.getFileById(imageFileId);
      // 插入图片到占位符位置,设置宽度(可根据需求调整)
      var insertedImage = body.insertImage(start, imageFile);
      insertedImage.setWidth(400); // 调整图片宽度,单位为像素
    } catch (err) {
      // 捕获权限或文件不存在的错误,插入提示文本
      parent.insertText(start, "图片加载失败:" + err.message);
    }
  } else {
    // 如果无法提取ID,插入提示
    parent.insertText(start, "无效的图片链接格式");
  }
}
  1. 完整修改后的代码:
// @ts-nocheck
function autoFillGoogleDocFromForm(e) {
  
  //e.values is an array of form values
  var timestamp = e.values[0];
  var email = e.values[1];
  var who = e.values[2];
  var employeeorcon = e.values[3];
  var location = e.values[4];
  var roomorarea = e.values[5];
  var type = e.values[6];
  var dateofworks = e.values[7];  
  var imageofcompletedcon = e.values[8];
  var checkedoffintext = e.values[9];
  var checkname = e.values[10];
  var checkco = e.values[11];
  var checkeddate = e.values[12];
 

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById("1WcYKvsRFbKK73J-ep66mR9drZyrkWap-x30rO-kVUcM"); 
  
  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById("1MeU3-N3BMqOPvoaSGr2XassibR2XajdN")
  var copy = file.makeCopy(roomorarea + '_' + timestamp, folder); 
  
  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId()); 
  
  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody(); 
  
  //Then we call all of our replaceText methods
  body.replaceText('{{location}}', location); 
  body.replaceText('{{room}}', roomorarea);   
  body.replaceText('{{completedby}}', who); 
  body.replaceText('{{checkedby}}', checkname); 
  body.replaceText('{{checkeddate}}', checkeddate);  
  body.replaceText('{{insdate}}', dateofworks); 
  body.replaceText('{{Empcon}}', employeeorcon);  
  body.replaceText('{{Type}}', type); 
  body.replaceText('{{methchk}}', checkedoffintext);  
  body.replaceText('{{checker}}', checkname); 
  body.replaceText('{{cocheck}}', checkco);   
  body.replaceText('{{datecheck}}', checkeddate); 

  // 处理图片插入
  var imagePlaceholder = '{{image}}';
  var searchResult = body.findText(imagePlaceholder);

  if (searchResult) {
    // 获取占位符的位置信息
    var element = searchResult.getElement();
    var start = searchResult.getStartOffset();
    var end = searchResult.getEndOffsetInclusive();
    var parent = element.getParent();
    
    // 删除占位符文本
    parent.deleteText(start, end);
    
    // 从Drive链接中提取文件ID(适配标准Drive链接格式:https://drive.google.com/file/d/[ID]/...)
    var imageIdMatch = imageofcompletedcon.match(/d\/([a-zA-Z0-9-_]+)\//);
    if (imageIdMatch) {
      var imageFileId = imageIdMatch[1];
      try {
        // 获取图片文件
        var imageFile = DriveApp.getFileById(imageFileId);
        // 插入图片到占位符位置,设置宽度(可根据需求调整)
        var insertedImage = body.insertImage(start, imageFile);
        insertedImage.setWidth(400); // 调整图片宽度,单位为像素
      } catch (err) {
        // 捕获权限或文件不存在的错误,插入提示文本
        parent.insertText(start, "图片加载失败:" + err.message);
      }
    } else {
      // 如果无法提取ID,插入提示
      parent.insertText(start, "无效的图片链接格式");
    }
  }
  
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose(); 
}

注意事项

  • 确保脚本有访问Google Drive中图片文件的权限
  • 如果表单返回的是直接的图片文件ID而非完整链接,可以去掉ID提取逻辑,直接使用imageofcompletedcon作为文件ID
  • 可根据需求调整setWidth的数值,或添加setHeight设置高度

内容的提问来源于stack exchange,提问作者Kevin Greenwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:50:23