Google Script生成嘉宾胸牌:格式与图片失效问题求助
解决Google Script生成嘉宾胸牌的两个问题:文本居中和图片复制
问题描述
- 文本字段可正常填充,但无法继承模板中的居中对齐设置
- 模板单元格内的图片无法复制到新生成的胸牌表格中
修改后的完整脚本
const g = { docId: '14Pa2L0gudkiDbDBQFXztY2Gd5J8u3hlmARaH0F_LIPE', }; function init_() { g.doc = DocumentApp.openById(g.docId); g.body = g.doc.getBody(); g.ss = SpreadsheetApp.getActive(); } function CreateGuestID() { init_(); const sh = g.ss.getSheetByName('guests'); [g.guestsHeaders, ...g.guestsData] = sh.getDataRange().getValues(); const templateTable = g.body.getTables()[0]; const templateCell = templateTable.getCell(0, 0).copy(); const numLines = templateCell.getNumChildren(); // 存储模板中的所有元素(段落+图片)及对应属性 const templateElements = []; for (let i = 0; i < numLines; i++) { const child = templateCell.getChild(i); const type = child.getType(); if (type === DocumentApp.ElementType.PARAGRAPH) { const text = child.getText(); const atts = {}; Object.entries(child.getAttributes()).forEach(([k, v]) => { if (!(v instanceof Object)) { atts[k] = v; } }); // 记录段落对齐方式 const alignment = child.getAlignment(); templateElements.push({ type: 'paragraph', text, attributes: atts, alignment }); } else if (type === DocumentApp.ElementType.INLINE_IMAGE) { // 复制图片元素 const image = child.copy(); templateElements.push({ type: 'image', image }); } } const bodyChildren = g.body.getNumChildren(); for (let i = bodyChildren - 2; i > 1; i--) { g.body.removeChild(g.body.getChild(i)); } const numRows = templateTable.getNumRows(); const numCols = templateTable.getRow(0).getNumCells(); let iCol = Infinity; let iRow = Infinity; let table; g.guestsData.forEach((recipient) => { if (iCol >= numCols) { iCol = 0; iRow++; } if (iRow >= numRows) { iRow = 0; table = g.body.appendTable(templateTable.copy()); table.setBorderWidth(0); table.getCell(0, 0).clear(); } const newCell = table.getCell(iRow, iCol); newCell.clear(); // 根据模板元素类型创建内容 templateElements.forEach((elem, i) => { if (elem.type === 'paragraph') { const newLine = merge_(elem.text, recipient); const par = newCell.insertParagraph(i, newLine); par.editAsText().setAttributes(elem.attributes); par.setForegroundColor(elem.attributes.FOREGROUND_COLOR); // 设置段落对齐 par.setAlignment(elem.alignment); } else if (elem.type === 'image') { // 插入复制的图片 newCell.insertInlineImage(i, elem.image.copy()); } }); iCol++; }); g.doc.saveAndClose(); } function merge_(text, recipient) { g.guestsHeaders.forEach((header, i) => { text = text.replace(`%${header}%`, recipient[i]); }); return text; }
关键改动说明
文本居中修复:
- 新增记录模板段落的
alignment(对齐方式)属性 - 在生成新段落时,调用
par.setAlignment(elem.alignment)继承模板的对齐设置
- 新增记录模板段落的
图片复制修复:
- 遍历模板单元格子元素时,判断并处理
INLINE_IMAGE类型元素 - 复制模板中的图片对象,在生成新单元格时插入复制后的图片
- 遍历模板单元格子元素时,判断并处理
内容的提问来源于stack exchange,提问作者user22283843
相关产品推荐
相关产品推荐

