有没有办法使用 Google Charts API 的 POST 方法通过 Google Apps 脚本获取 QR 代码图像?

Jos*_*aum 4 charts post qr-code google-visualization google-apps-script

我正在使用 Google 脚本生成活动门票,该门票包含一个二维码,可转至预先填写的 Google 表单链接。由于它是预先填充的,因此该字符串相当长,并且用于创建 QR 码的 Google Charts API 不会使用 GET 请求接受这么长的文本字符串,但我找不到任何有关如何编写 POST 请求的文档进入 Apps 脚本。如何在 Apps 脚本中生成 POST 请求,该请求将返回 QR 代码的图像,然后我可以将其插入到文档中?

我已经尝试过 GET 请求,它会在将 URL 编码为 QR 码之前截断 URL。这让我看到了 Google 表单,但不是链接生成的预填充版本(实际上 Google 非常聪明,它在仍然提供可用 URL 的地方截断了字符串,但那是另一天的事了…… )

我还尝试过 HtmlService 使用 POST 方法和 Charts API 以 HTML 表单形式呈现 QR 代码,该表单会在加载该 HTML 时自动提交。如果我使用 showSidebar(),这将在新选项卡中打开图像,但我还没有弄清楚如何返回该图像以便将其插入到文档中。

我还尝试使用 HTML 创建一个 blob,然后将该 blob 保存为 PNG,但根据我所做的研究,.getAs() 方法在转换 HTML 时不会渲染图像。

renderQR 函数:

function renderQR(inputUrl) {
  var html = HtmlService.createTemplateFromFile('QREncode.html');
  html.url = inputUrl;  
  var rendered = html.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setHeight(300)
    .setWidth(300);
 return rendered;   
}
Run Code Online (Sandbox Code Playgroud)

QREncode.html 文件:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script type='application/javascript'>
    // Send the POST when the page is loaded,
    // which will replace this whole page with the retrieved chart.
    function loadGraph() {
      var frm = document.getElementById('post_form');
      if (frm) {
       frm.submit();
      }
    }
    </script>
  </head>
  <body onload="loadGraph()">
    <form action='https://chart.googleapis.com/chart' method='POST' id='post_form'>
       <input type='hidden' name='cht' value='qr' />
      <input type='hidden' name='chl' value='<?= url ?>' />
      <input type='hidden' name='chs' value='300x300' />
      <input type='submit'/>
    </form>    
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我将 renderQR() 函数的返回值视为图像时,Apps 脚本会给出错误,指出它是“无效图像数据”,这是有道理的 - 但如何将其转换为图像,或者是否有更好的方法或者我可以用更简单的方式来做到这一点?

Jer*_*emy 5

您需要在 Apps 脚本中获取二维码,而不是在浏览器中:

  var imageData = UrlFetchApp.fetch('https://chart.googleapis.com/chart', {
    'method' : 'post',
    'payload' : {
      'cht': 'qr',
      'chl': 'https://google.com',
      'chs': '300x300'
  }}).getContent();
Run Code Online (Sandbox Code Playgroud)