【问题标题】:Google Apps Script - Images not showing when creating PDF from HTMLGoogle Apps 脚本 - 从 HTML 创建 PDF 时不显示图像
【发布时间】:2021-02-04 02:25:05
【问题描述】:

我正在尝试编写一个脚本,该脚本将输出带有已输入表单的值的 PDF。在此 PDF 中,我想在页面顶部添加一个徽标,该徽标是 Google Drive 文件夹中的图像。

基于this question(及其他),需要将图片转换为base64,然后添加到HTML中。

我的问题是即使我这样做了,图像仍然没有显示在 PDF 文件中。

这是我当前的代码,只是尝试输出带有图像的 PDF,仅此而已

function htmlToPDF() {
  var url = "https://drive.google.com/uc?export=view&id=1pHu-JPLA4Ml6R5Mc7pktLtqCAcGepLMG"
  var img = UrlFetchApp.fetch(url)
  var b64 = img.getBlob().getContentType() + ";base64," + Utilities.base64Encode(img.getBlob().getBytes());
  var html_img = "<img src=\"data:" + b64 + "\" >";

  var blob = Utilities.newBlob(html_img, "text/html", "text.html")
  var pdf = blob.getAs("application/pdf");
  DriveApp.getFolderById('1o-yYvlNmdRYsH-J6b31wrT2GYfkCQEGG').createFile(pdf).setName("text.pdf");
}

这是我运行此脚本时得到的结果

谢谢!

【问题讨论】:

  • 我认为您的脚本有效,并且图像显示在PDF数据中。虽然我不确定这是否是直接解决方案,例如,当您将export=view 修改为export=download 时,您会得到什么结果?顺便问一下,你的图片是什么 mimeType?
  • @Tanaike 是的,将其更改为 export=download 没有任何影响。对于 mimeType,.getContentType() 方法返回 text/html,这就是你要找的吗?
  • 感谢您的回复。我不得不为我糟糕的英语水平道歉。关于For mimeType, the .getContentType() method returns text/html,在这种情况下,你要放的图片是HTML数据?

标签: html image pdf google-apps-script


【解决方案1】:

修改代码

/**
 * Creates an HTML <img> tag from an image file ID
 */
function imgToHtmlTag(fileId) {
  let file = DriveApp.getFileById(fileId)
  let fileBlob = file.getBlob()
  let imgData = fileBlob.getContentType() + ';base64,' + Utilities.base64Encode(fileBlob.getBytes())

  return "<img src='data:" + imgData + "' />"
}

/**
 * Creates a pdf called "test" in your drive based on HTML input
 */
function createPdfFromHtml(html) {
  var blob = HtmlService.createHtmlOutput(html);
  blob = blob.getBlob();
  var pdf = blob.getAs("application/pdf");
  DriveApp.createFile(pdf).setName("test.pdf");
}

/**
 * Function to test above functions
 */
function test() {
  var fileId = "[IMG_DRIVE_FILE_ID]"
  let html = imgToHtmlTag(fileId)
  createPdfFromHtml(html)
}
}

我从您的脚本中更改了几处:

  • 我没有使用urlFetchApp 来获取图像,而是使用了内置的DriveApp
  • 我将其重构为单独的函数,以使其更易于理解。

这个脚本适合我。我不确定您的脚本失败的确切原因,但如果这也不起作用,请尝试更改图像文件。

参考

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多