如何通过AppScript实现Google幻灯片中文字的“形状适配文字”调整?
问题描述
尝试调整Google Slides中已渲染文字的自动适配效果,调用自定义的updateTextAutoFit函数时触发API错误:
Failed with error API call to slides.presentations.batchUpdate failed with error: Invalid requests[0].updateShapeProperties: The object (SLIDES_API1782835896_0) could not be found.
附相关代码:
function updateTextAutoFit(presentationId: string, objectId: string) { const requests: GoogleAppsScript.Slides.Schema.Request[] = [ { updateShapeProperties: { objectId: objectId, fields: "autofit", shapeProperties: { // @ts-ignore autofit: { autofitType: "SHAPE_AUTOFIT", }, }, }, }, ]; try { const slide = Slides.Presentations?.batchUpdate( { requests: requests }, presentationId ); return slide; } catch (e: any) { Logger.log("Failed with error %s", e.message); } } const titleText = createTextBox({ slide, text: title, fontSize: 28, isBold: true, position: titlePosition, presentationId, }); updateTextAutoFit(presentationId, id);
解决方案
1. 修正变量传递错误
你调用updateTextAutoFit时传入的id并非刚创建的文本框对象ID,应该使用createTextBox返回的titleText中的对象ID:
// 替换原调用代码 updateTextAutoFit(presentationId, titleText.objectId);
注意:确保createTextBox函数正确返回包含objectId的对象(通常创建形状后,Slides API会自动生成并返回该ID)。
2. 验证自动适配类型
根据需求确认autofitType的取值:
SHAPE_AUTOFIT: 调整形状大小以适配文本TEXT_AUTOFIT: 调整文本字号以适配形状NONE: 关闭自动适配
3. 可选:创建文本框时直接设置自动适配
如果不需要单独调用函数,也可以在创建文本框的请求中直接添加自动适配配置,避免后续调用出错:
// 示例:在createTextBox内部的batchUpdate请求中加入autofit设置 function createTextBox(options) { const customObjectId = "TEXT_BOX_" + Date.now(); // 生成唯一ID const requests = [ { createShape: { objectId: customObjectId, shapeType: "TEXT_BOX", elementProperties: { pageObjectId: options.slide.objectId, size: { width: { magnitude: 500, unit: "PT" }, height: { magnitude: 100, unit: "PT" } }, transform: { scaleX: 1, scaleY: 1, translateX: options.position.x, translateY: options.position.y, unit: "PT" } } } }, { insertText: { objectId: customObjectId, text: options.text } }, { updateShapeProperties: { objectId: customObjectId, fields: "autofit", shapeProperties: { autofit: { autofitType: "SHAPE_AUTOFIT" } } } }, { updateTextStyle: { objectId: customObjectId, textRange: { type: "ALL" }, style: { fontSize: { magnitude: options.fontSize, unit: "PT" }, bold: options.isBold }, fields: "fontSize,bold" } } ]; const response = Slides.Presentations.batchUpdate({ requests }, options.presentationId); return { objectId: response.replies[0].createShape.objectId }; }
内容的提问来源于stack exchange,提问作者Anurag Bhagsain
相关产品推荐
相关产品推荐

