You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Apps Script的HTML转PDF中使用自定义字体?

问题:Google Apps Script生成PDF时自定义字体无法生效?

我尝试用Google Apps Script实现一个基于HTML文件的PDF生成器,但自定义字体始终无法应用。试过通过base64格式加载字体没成功,也尝试用@font-face引入Google字体,但在转换为PDF前字体似乎没有被获取到(不过部署脚本后通过doGet(e)访问页面时字体显示正常)。

我的代码:

Google Apps Script函数

function htmlToPdf() {
  var fileIdOfFontFile = "1xXWmKZ2wRzWq_4DWfeIK67QKFVkF_nVu";
  var fontBlob = DriveApp.getFileById(fileIdOfFontFile).getBlob();

  var htmlTemplate = HtmlService.createTemplateFromFile("site");
  htmlTemplate.fontData = fontBlob.getContentType() + ';base64,' + Utilities.base64Encode(fontBlob.getBytes());

  var pdf_html = htmlTemplate.evaluate().getContent();

  var blob = Utilities.newBlob(pdf_html, MimeType.HTML).getAs(MimeType.PDF);
  DriveApp.createFile(blob);
}

HTML文件(site.html)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <style>
    @font-face {
      font-family: "Gloria Hallelujah";
      src: url(<?= fontData ?>);
    }
    * {
      font-family: "Gloria Hallelujah";
    }
  </style>

  <body>
    <p>test</p>
  </body>
</html>

解决方案

修改HTML中的@font-face规则,在url()内添加data:前缀并包裹引号:

原代码:

@font-face {
  font-family: "Gloria Hallelujah";
  src: url(<?= fontData ?>);
}

修改后:

@font-face {
  font-family: "Gloria Hallelujah";
  src: url("data:<?= fontData ?>");
}

有意思的是,我之前尝试把data:作为字符串传入变量时效果不对,最后把data:直接保留在HTML文件里就解决了问题。


内容的提问来源于stack exchange,提问作者sk_rp_ta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:32:43