Record your life!
DashboardMy Blogs
如何解决gotenberg渲染字体不正确的问题?
Blog
csshtml
By sakopqiu2025-11-05 09:20

我们的设计稿中使用了Google的Inter字体。 我自然而然的把字体的声明放置在了html的声明中

 <link rel="preconnect" href="https://fonts.googleapis.com">
 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
 <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

这段在browser里渲染都是正常的,在gotenberg的docker方式去生成的时候,时有时无。 综其原因还是Inter字体是比较大的,大约20MB左右,gotenberg默认的渲染似乎不会去等待字体的下载就生成了。

所以一个好的方式是,把字体安装进入docker镜像里

  • 步骤1, 在google下载inter字体文件,Inter.zip
  • 步骤2,本地生成下面这个Dockerfile
# 生成新的docker镜像,并
FROM gotenberg/gotenberg:8

USER root
RUN apt-get update && apt-get install -y unzip fontconfig 
RUN mkdir -p /usr/share/fonts/truetype/inter 
COPY Inter.zip /usr/share/fonts/truetype/inter/Inter.zip
RUN cd /usr/share/fonts/truetype/inter && unzip Inter.zip && rm Inter.zip 
# 这个命令会去把新字体注册到系统中
RUN fc-cache -fv
USER gotenberg
  • 步骤3,docker build -t gotenberg2 ., 生成一个新的gotenberg2镜像
  • 步骤4,启动新的镜像 docker run -d --rm -p 3005:3000 gotenberg2:latest
  • 步骤5,使用新镜像进行文件生成pdf
curl \
 --request POST 'http://localhost:3005/forms/chromium/convert/html' \
--form files=@index.html \
-o index.pdf 
Edit