在PDF中,fontface似乎是从URL加载的,但不显示

2024-05-16 19:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Django应用程序使用WeasyPrint按需生成PDF。我使用的是WeasyPrint 52.4和Django 3.2

我一直在使用系统字体,这一直工作得很好。现在我尝试使用本地字体。现在,我正在通过localhost加载静态资产,指向Django的静态服务器,这样我就可以看到请求进入并确保加载了正确的内容

以下是WeasyPrint的名称:

font_config = weasyprint.fonts.FontConfiguration()
css = weasyprint.CSS(url='http://localhost:8000/static/kits/static/report.css', font_config=font_config)
return weasyprint.HTML(
    string='<h1>Hello world</h1>',
    encoding='utf-8',
).write_pdf(
    stylesheets=[css],
    font_config=font_config,
)

这是我的CSS:

@font-face {
  font-family: 'foobar';
  src: url(http://localhost:8000/static/Oxygen-Regular.ttf) format('truetype');
  font-weight: 400;
}

@font-face {
  font-family: 'foobar';
  src: url(http://localhost:8000/static/Oxygen-Bold.ttf) format('truetype');
  font-weight: 700;
}

:root {
  font-family: 'foobar', sans-serif;
  color: red;
}

文本正确地涂成红色,因此我知道CSS正在加载。我可以从服务器日志中看到字体请求成功,这向我表明WeasyPrint正在正确获取字体:

2021-04-07 09:57:32,147 INFO    "GET /static/mycss.css HTTP/1.1" 200 5748
2021-04-07 09:57:32,193 INFO    "GET /static/Oxygen-Regular.ttf HTTP/1.1" 200 46440
2021-04-07 09:57:32,200 INFO    "GET /static/Oxygen-Bold.ttf HTTP/1.1" 200 47096

但是PDF显示了回退字体。我错过了什么


Tags: djangoconfiglocalhosthttpurl字体staticttf