【问题标题】:Setting link URL with Google Docs API doesn't result in update of image使用 Google Docs API 设置链接 URL 不会导致图像更新
【发布时间】:2021-06-16 02:55:16
【问题描述】:

我正在尝试使用具有更新 URL 的新图像来更新占位符图像。该 URL 实际上是我在其他上下文中成功使用的有效 Google 静态地图 URL。我正在使用 Google Document API 来操作文档。按照我一直在使用的代码:

 var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
  var imageMap = element.asInlineImage();
  // if there was an image found in document
  if (imageMap != null) {
     // get current parent and index inside parent
    var parent = imageMap.getParent();
    var childIndex = parent.getChildIndex(imageMap);
    // remove image from paragraph
    imageMap = imageMap.removeFromParent();
    // get static image url for territory
    var url = getStaticMapURLForTerritory(id);
    Logger.log(url);
    imageMap.setLinkUrl(url);
    // create a new image
    parent.insertInlineImage(childIndex, imageMap)
  }

这似乎工作正常,因为它确实正确更新了图像 url。但是,图像本身(url 的结果)不会更新。当我单击链接 URL 时,它会返回正确的图像。

有没有办法强制重新获取与 URL 关联的图像 blob?我也尝试使用 UrlFetchApp,但抱怨缺少大小参数(google static api),该参数肯定包含在 url 字符串中并且在最大 640x640 范围内。

我已经用尽了所有的选择,除非......

TIA,--保罗

【问题讨论】:

    标签: image google-maps url google-apps-script google-docs-api


    【解决方案1】:

    setLinkUrl 只这样做:设置链接。要实际添加新图像,您必须获取它的 blob:

    function replaceImage() {
      // [...]
    
      // get static image url for territory
      const url = getStaticMapURLForTerritory(id)
      const response = UrlFetchApp.fetch(url)
    
      // create a new image
      parent.insertInlineImage(childIndex, response.getBlob())
        .setAltDescription(img.getAltDescription())
        .setAltTitle(img.getAltTitle())
        .setWidth(img.getWidth())
        .setHeight(img.getHeight())
        .setLinkUrl(url)
    }
    

    参考

    【讨论】:

    • 谢谢马蒂。不幸的是,我在 UrlFetchApp.fetch(url) 上遇到了异常。该 URL 是有效的,因为我可以将其复制并粘贴到任何可以成功获取它并显示图像的浏览器的地址字段中。不确定是什么导致了这个异常?顺便说一句:静态图像使用由竖线“|”分隔的样式器输入。我是否需要转义这些符号才能使 UrlFetchApp.fetch 工作?
    • 同时,我在样式器说明中转义了似乎已解决问题的“管道”字符。显然,它混淆了 UrlFetchApp。谢谢。
    • @PaulvanHagen 是的,您需要对 URL 进行编码(有些库会为您完成,但不是全部)。另外,如果这个答案对你有帮助,consider accepting it.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多