如何通过Apps Script在Google Docs插入图片时自动旋转指定图片
实现Google Docs图片占位符替换时按指定角度旋转的解决方案
步骤1:更新占位符配置,添加旋转角度参数
在需要旋转的图片占位符配置中新增rotation字段,指定旋转角度(正数为顺时针,负数为逆时针,单位:度):
"{{P&I}}": { cell: "E234", width: 570, horizontalAlignment: DocumentApp.HorizontalAlignment.CENTER, rotation: 90 // 示例:顺时针旋转90度 },
步骤2:修改替换图片的函数逻辑
在插入图片并设置宽高的代码后,添加旋转处理逻辑,同时适配旋转后的宽高避免变形:
for (var placeholder in placeholders) { const foundElement = body.findText(placeholder); if (foundElement) { var imageId = strukturSheet.getRange(placeholders[placeholder].cell).getValue(); // 检查图片ID是否为空 if (imageId) { var imageFile = DriveApp.getFileById(imageId); const imageBlob = imageFile.getBlob(); const element = foundElement.getElement(); const text = element.asText(); // 将占位符替换为空文本 text.replaceText(placeholder, " "); const container = text.getParent(); const index = container.getChildIndex(text); const image = container.insertInlineImage(index, imageBlob); const config = placeholders[placeholder]; let imageWidth = config.width; let imageAspectRatio = image.getWidth() / image.getHeight(); let imageHeight = imageWidth / imageAspectRatio; // 处理图片旋转及宽高适配 if (config.rotation) { const rotation = config.rotation % 360; image.setRotation(rotation); // 旋转90/270度时,宽高互换以保持比例 if ([90, 270, -90, -270].includes(rotation)) { [imageWidth, imageHeight] = [imageHeight, imageWidth]; } } image.setWidth(imageWidth).setHeight(imageHeight); const paragraph = image.getParent(); if (paragraph.getType() === DocumentApp.ElementType.PARAGRAPH) { paragraph.setAlignment(config.horizontalAlignment); } } else { const element = foundElement.getElement(); const text = element.asText(); const newText = text.getText().replace(placeholder, "").trim(); if (newText === "") { const paragraph = element.getParent(); paragraph.removeFromParent(); } else { text.replaceText(placeholder, ""); } } } }
关键说明
setRotation()方法:Google Apps Script的InlineImage对象原生支持该方法,直接传入角度值即可完成旋转- 宽高适配:旋转90/270度(或对应负值)时,图片宽高比例反转,需互换设置的宽高值避免拉伸变形
- 角度取模:对旋转角度取模360,确保角度始终在0-359度的有效范围内
内容的提问来源于stack exchange,提问作者Pokket
相关产品推荐
相关产品推荐

