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

如何用Google Apps Script替换文本占位符为图片并实现四张图片同尺寸方形排版

解决方案:在Google Docs中插入等尺寸方形排列的四张图片

我会帮你整合现有代码和定位图片的功能,实现四张图片等尺寸、方形排列的需求。下面是完整的实现方案,包含两种思路:固定坐标排列和替换文本占位符排列,你可以根据模板情况选择。


1. 完整代码实现(包含两种方式)

首先,把以下代码复制到你的Google Apps Script编辑器中:

// 辅助函数:从Google Drive URL提取File ID
function getFileIdFromUrl(url) {
  if (!url) return null;
  const idMatch = url.match(/[\w\_\-]{25,}/);
  return idMatch ? idMatch[0] : null;
}

// 辅助函数:插入固定位置的定位图片(用于固定坐标排列)
function insertPositionedImage(body, blob, leftOffset, topOffset, width, height) {
  const positionedImage = body.appendPositionedImage(blob);
  positionedImage.setWidth(width);
  positionedImage.setHeight(height);
  positionedImage.setLeftOffset(leftOffset);
  positionedImage.setTopOffset(topOffset);
  // 设置环绕方式,可选:INLINE / WRAP_TEXT / BREAK_TEXT
  positionedImage.setLayout(DocumentApp.PositionedLayout.WRAP_TEXT);
  return positionedImage;
}

// 辅助函数:替换文本占位符为图片(用于占位符替换方案)
function replacePlaceholderWithImage(body, placeholder, blob, imgSize) {
  const searchResult = body.findText(placeholder);
  if (!searchResult) {
    Logger.log(`Placeholder ${placeholder} not found`);
    return;
  }
  const element = searchResult.getElement();
  const startOffset = searchResult.getStartOffset();
  const endOffset = searchResult.getEndOffsetInclusive();
  
  // 插入图片到占位符位置
  const positionedImage = element.getParent().appendPositionedImage(blob);
  positionedImage.setWidth(imgSize);
  positionedImage.setHeight(imgSize);
  positionedImage.setLayout(DocumentApp.PositionedLayout.WRAP_TEXT);
  
  // 删除占位符文本
  element.deleteText(startOffset, endOffset);
}

// 主函数:创建文档并插入图片
function createDocument() { 
  const sheetId = '1Yy70i8aQ3GZEp5FE5mhO458Bmivu01ZeykG0GFZmrVo';
  const templateId = '1ajVQxJAgGxXF3ivkaWL5WEv2xhiJc9r0YwxLH5Hm17w';
  
  // 获取表格数据
  const tactics = Sheets.Spreadsheets.Values.get(sheetId, 'A5:J26');
  if (!tactics.values) return;

  for(let i = 0; i < tactics.values.length; i++){ 
    const row = tactics.values[i];
    const projectID = row[0];
    const projectName = row[1];

    // 复制模板并重命名
    const templateFile = DriveApp.getFileById(templateId);
    const newDoc = templateFile.makeCopy(`${projectID}overview`);
    const doc = DocumentApp.openById(newDoc.getId());
    const body = doc.getBody();

    // 替换文本占位符
    body.replaceText('##ProjectID##', projectID);
    body.replaceText('##ProjectName##', projectName);

    // 获取四张图片的Blob
    const imgUrls = [row[10], row[11], row[12], row[13]];
    const imgBlobs = [];
    for(const url of imgUrls) {
      const fileId = getFileIdFromUrl(url);
      if (!fileId) {
        Logger.log(`Invalid image URL: ${url}`);
        imgBlobs.push(null);
        continue;
      }
      try {
        const imgBlob = DriveApp.getFileById(fileId).getBlob();
        imgBlobs.push(imgBlob);
      } catch(e) {
        Logger.log(`Failed to get image: ${e.message}`);
        imgBlobs.push(null);
      }
    }

    // --- 方式1:固定坐标排列成2x2方形 ---
    // 可根据需求调整以下参数
    const imgSize = 200; // 图片宽高(统一尺寸)
    const spacing = 25; // 图片之间的间距
    const startX = 50;  // 起始X坐标
    const startY = 150; // 起始Y坐标

    // 插入四张图片
    if(imgBlobs[0]) insertPositionedImage(body, imgBlobs[0], startX, startY, imgSize, imgSize);
    if(imgBlobs[1]) insertPositionedImage(body, imgBlobs[1], startX + imgSize + spacing, startY, imgSize, imgSize);
    if(imgBlobs[2]) insertPositionedImage(body, imgBlobs[2], startX, startY + imgSize + spacing, imgSize, imgSize);
    if(imgBlobs[3]) insertPositionedImage(body, imgBlobs[3], startX + imgSize + spacing, startY + imgSize + spacing, imgSize, imgSize);

    // --- 方式2:替换模板中的文本占位符(推荐,更灵活)---
    // 先在模板文档中插入四个占位符:##IMG1##、##IMG2##、##IMG3##、##IMG4##,并手动排成方形
    // 然后注释掉方式1的代码,取消注释下面的代码
    // const imgSize = 200;
    // if(imgBlobs[0]) replacePlaceholderWithImage(body, '##IMG1##', imgBlobs[0], imgSize);
    // if(imgBlobs[1]) replacePlaceholderWithImage(body, '##IMG2##', imgBlobs[1], imgSize);
    // if(imgBlobs[2]) replacePlaceholderWithImage(body, '##IMG3##', imgBlobs[2], imgSize);
    // if(imgBlobs[3]) replacePlaceholderWithImage(body, '##IMG4##', imgBlobs[3], imgSize);

    // 保存文档
    doc.saveAndClose();
  }
}

2. 关键部分解释

(1)图片URL转Blob

通过getFileIdFromUrl函数提取Drive文件ID,再用DriveApp.getFileById(fileId).getBlob()获取图片的Blob对象,这是插入图片到Docs的必要格式。

(2)固定坐标排列

通过insertPositionedImage函数设置每张图片的左偏移量、上偏移量和统一宽高,实现2x2的方形排列。你可以调整imgSize、spacing、startX、startY这几个参数来控制图片大小和位置。

(3)占位符替换排列(推荐)

这种方式更灵活:

  1. 先在你的模板文档中,手动插入四个文本占位符:##IMG1##、##IMG2##、##IMG3##、##IMG4##,并把它们排成你想要的方形布局(调整占位符的位置和间距)。
  2. 注释掉代码中「方式1」的部分,取消「方式2」的注释。
  3. 运行代码后,占位符会被替换成等尺寸的图片,保留你手动设置的布局。

3. 注意事项

  • 确保你的脚本有足够的权限:运行时会请求访问Google Drive和Docs的权限,授权即可。
  • 如果图片URL无效或无访问权限,代码会记录日志并跳过该图片,避免整个脚本崩溃。
  • 图片的环绕方式可以通过setLayout调整:INLINE会让图片和文本在同一行,WRAP_TEXT允许文本环绕图片,BREAK_TEXT会让图片单独占一行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:17:50