如何解决Google Apps Script替换Doc文本为Sheets单元格图片显示cellimage的问题
解决方案
问题原因
body.replaceText 仅支持文本内容替换,无法直接插入图片,所以你之前的操作只能输出二维码对应的文本内容,无法展示图片。
修改步骤
- 删除原来代码中
body.replaceText("{qrcode}",qrcode);这一行 - 新增占位符定位、图片插入逻辑,可直接将二维码设置为150×150像素的尺寸
完整修改后的createPDF函数代码
function createPDF(number,model,fors,length,width,thickness,litres,notes,blank,orders,dates,finSetup,lamination,artwork,finSystem,leash,finish,phoneNumber,shipping,qrcode,pdfName,docFile,tempFolder,pdfFolder) { const tempFile = docFile.makeCopy(tempFolder); const tempDocFile = DocumentApp.openById(tempFile.getId()); const body = tempDocFile.getBody(); body.replaceText("{number}",number); body.replaceText("{model}",model); body.replaceText("{for}",fors); body.replaceText("{length}",length); body.replaceText("{width}",width); body.replaceText("{thickness}",thickness); body.replaceText("{litres}",litres); body.replaceText("{notes}",notes); body.replaceText("{blank}",blank); body.replaceText("{orderTakenBy}",orders); body.replaceText("{dateTaken}",dates); body.replaceText("{finSetup}",finSetup); body.replaceText("{lamination}",lamination); body.replaceText("{artwork}",artwork); body.replaceText("{finSystem}",finSystem); body.replaceText("{leash}",leash); body.replaceText("{finish}",finish); body.replaceText("{phoneNumber}",phoneNumber); body.replaceText("{shippingCo}",shipping); // 新增二维码替换逻辑开始 const qrPlaceholder = "{qrcode}"; const foundRange = body.findText(qrPlaceholder); if (foundRange) { const startOffset = foundRange.getStartOffset(); const textElement = foundRange.getElement().asText(); // 删除占位符文本 textElement.deleteText(startOffset, startOffset + qrPlaceholder.length - 1); let qrBlob; // 按你实际的二维码存储方式二选一即可: // 选项1:表格中qrcode列存的是二维码要承载的文本内容,直接生成二维码 const qrContent = qrcode; const qrGenUrl = `https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=${encodeURIComponent(qrContent)}&choe=UTF-8`; qrBlob = UrlFetchApp.fetch(qrGenUrl).getBlob(); // 选项2:表格中qrcode列是用IMAGE函数插入的二维码,替换为下面的代码提取链接获取图片 // 注意如果用这个选项,需要删除上面选项1的代码 // const qrCell = currentSheet.getRange(foundRowIndex, 20); // 20对应qrcode所在的列号,按实际修改 // const qrFormula = qrCell.getFormula(); // const qrImageUrl = qrFormula.match(/"([^"]+)"/)[1]; // qrBlob = UrlFetchApp.fetch(qrImageUrl).getBlob(); // 插入图片并设置尺寸 const insertedQr = textElement.getParent().asParagraph().insertInlineImage(startOffset, qrBlob); insertedQr.setWidth(150); insertedQr.setHeight(150); } // 新增二维码替换逻辑结束 tempDocFile.saveAndClose(); const pdfContentBlob = tempFile.getAs(MimeType.PDF); pdfFolder.createFile(pdfContentBlob).setName(pdfName); tempFolder.removeFile(tempFile); }
注意事项
- 首次运行会要求授权UrlFetchApp的访问权限,正常授权即可
- 如果你的二维码是直接插入到单元格的图片(不是用IMAGE函数生成),需要额外用
getImages()方法读取单元格内的图片Blob,替换上面获取qrBlob的逻辑即可 - 插入的二维码会和原占位符在同一个段落内,位置和原占位符一致
内容的提问来源于stack exchange,提问作者skelts
相关产品推荐
相关产品推荐

