使用Google Apps Script实现Google幻灯片文本框文本居中对齐
解决Google Apps Script幻灯片文本框文本居中报错问题
你的代码核心功能正常,但文本居中报错的原因是直接通过getParagraphs()[0]获取段落时,可能出现段落不存在(比如文本为空)或者索引越界的情况。另外,更稳妥的方式是对文本框内的所有文本段落统一设置对齐方式,而不是仅针对第一个段落。
修改后的代码
function testinsertTextOnImage() { const fileId = "1PU6GexJ....tiNkwRum2xYxYP"; const sheetId = "1_5bZsO6YJb8eS....9sgIao9C1uYxt_z2GBDjw"; const columns = ["A", "B", "C"]; const sheet = SpreadsheetApp.openById(sheetId).getSheetByName("Blad1"); const lastRow = sheet.getLastRow(); const texts = columns.map((column) => sheet.getRange(column + lastRow).getValue()); const textProperties = [ { text: texts[0], left: 500, top: 475, width: 880, height: 80, fontSize: 150, fontFamily: "Tangerine", alignment: SlidesApp.ParagraphAlignment.CENTER, }, { text: texts[1], left: 320, top: 660, width: 1000, height: 120, fontSize: 30, fontFamily: "Questrial", alignment: SlidesApp.ParagraphAlignment.CENTER, }, { text: texts[2], left: 920, top: 830, width: 180, height: 60, fontSize: 30, fontFamily: "Questrial", alignment: SlidesApp.ParagraphAlignment.CENTER }, ]; const file = DriveApp.getFileById(fileId); const blob = file.getBlob(); const size = ImgApp.getSize(blob); const presentation = { title: "Result", width: { unit: "pixel", size: size.width }, height: { unit: "pixel", size: size.height }, }; const presentationId = DocsServiceApp.createNewSlidesWithPageSize(presentation); const slides = SlidesApp.openById(presentationId); const slide = slides.getSlides()[0]; slide.insertImage(blob); textProperties.forEach(({ text, left, top, width, height, fontSize, fontFamily, alignment }) => { const textBox = slide.insertTextBox(text, left, top, width, height); const textRange = textBox.getText(); // 设置文本样式 textRange.getTextStyle().setFontSize(fontSize).setFontFamily(fontFamily); // 对所有段落设置对齐方式,避免索引报错 const paragraphs = textRange.getParagraphs(); paragraphs.forEach(paragraph => paragraph.setAlignment(alignment)); }); slides.saveAndClose(); const obj = Slides.Presentations.Pages.getThumbnail( presentationId, slide.getObjectId(), { "thumbnailProperties.thumbnailSize": "LARGE", "thumbnailProperties.mimeType": "PNG", } ); const url = obj.contentUrl.replace(/=s\d+/, "=s" + size.width); const resultBlob = UrlFetchApp.fetch(url) .getBlob() .setName("Result_" + file.getName()); DriveApp.createFile(resultBlob); DriveApp.getFileById(presentationId).setTrashed(true); }
关键修改点
- 替换原来单一获取
getParagraphs()[0]的方式,改为遍历所有段落设置对齐,避免因文本为空或段落结构变化导致的索引越界错误 - 先获取完整的文本范围
textRange,再统一操作样式和对齐,代码更健壮
额外注意事项
- 确保你使用的字体(Tangerine、Questrial)在Google幻灯片中可用,避免因字体不存在导致的样式失效
- 检查文本框的宽高设置是否足够容纳文本,避免文本换行后对齐效果不符合预期
内容的提问来源于stack exchange,提问作者MvD
相关产品推荐
相关产品推荐

