调用API获二进制图片后插入Google文档的Google Apps Script问题
解决Google Apps Script插入API返回的二维码图片到Google文档的问题
错误原因
你使用的Blob、document.createElement、URL.createObjectURL都是浏览器端专属的Web API,而Google Apps Script运行在Google的服务器环境中,不存在这些对象,因此会抛出ReferenceError: Blob is not defined错误。
正确解决方案
利用Google Apps Script原生的API来处理二进制响应并插入图片,步骤如下:
1. 修改APICall函数,返回可直接使用的Blob
UrlFetchApp的响应对象自带getBlob()方法,可直接将API返回的二进制图片转为GAS支持的Blob类型:
function APICall() { const url = "https://api.qr-code-generator.com/v1/create?access-token=dAlKmUnRsrPIFBLY_ix5YU0LRuMsNgM9MnFTmVHJwD4JRAeBmdzrPmmUAqi9zNyX"; const options = { method: "post", payload: { frame_name: "no-frame", qr_code_text: "https://www.qr-code-generator.com/", image_format: "PNG", qr_code_logo: "scan-me-square", download: 1 } }; const response = UrlFetchApp.fetch(url, options); // 根据API返回的图片格式设置MIME类型,这里是PNG return response.getBlob().setContentType("image/png"); }
2. 修改QRify函数,替换文本为图片
replaceText只能替换文本内容,无法直接插入图片。需要先找到<<QR>>文本的位置,删除文本后插入图片:
function QRify() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const head = doc.getHeader(); const foot = doc.getFooter(); const replaceText = "<<QR>>"; const qrBlob = APICall(); // 处理正文、页眉、页脚中的<<QR>> if (body) replaceTextWithImage(body, replaceText, qrBlob); if (head) replaceTextWithImage(head, replaceText, qrBlob); if (foot) replaceTextWithImage(foot, replaceText, qrBlob); } // 辅助函数:批量替换指定容器中的文本为图片 function replaceTextWithImage(container, searchText, imageBlob) { let foundElement = container.findText(searchText); // 循环处理所有匹配的文本 while (foundElement) { const textElement = foundElement.getElement(); const startOffset = foundElement.getStartOffset(); const endOffsetInclusive = foundElement.getEndOffsetInclusive(); // 删除匹配的文本内容 textElement.deleteText(startOffset, endOffsetInclusive); // 在原文本位置插入二维码图片 textElement.insertImage(startOffset, imageBlob); // 查找下一个匹配项 foundElement = container.findText(searchText, foundElement); } }
关键说明
- 如果API返回的是SVG格式,只需将
setContentType改为"image/svg+xml"即可,GAS会自动识别并插入SVG图片。 - 辅助函数
replaceTextWithImage会遍历所有匹配的<<QR>>文本,确保文档中所有标记都被替换为二维码图片。
内容的提问来源于stack exchange,提问作者Dylan Banta
相关产品推荐
相关产品推荐

