我很难在 PDF 文档中将字体设置为 Open Sans。我使用 python 使用 jinja 模板创建两个 html 文件,然后将它们每个转换为 PDF 文件,然后将它们合并在一起。我只能说,有时这些 PDF 中的一个具有正确的字体,有时另一个具有正确的字体,但尽管具有相同的代码,但从来没有同时出现过。我也对这种不一致感到困惑,因为它似乎与我所做的更改无关。我尝试下载字体样式 .tff 文件,以防错误是由于无法从互联网下载而引起的,但这没有帮助。
问题似乎出在我的 html/css 配置和转换为 PDF 的过程中。目前的设置是这样的:
<head>
<meta name="user-style-sheet" content="True" charset="utf-8" />
</head>
<style>
/* @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap'); */
@font-face {
font-family: 'Open Sans';
src: url('/templates/shared/Open_Sans/static/OpenSans_Condensed-Light.ttf');
}
body {
font-family: 'Open Sans';
}
p {
font-family: 'Open Sans';
font-size: medium;
}
</style>
我错过了什么?
WkHTMLtoX 已退役(生命周期结束),因此不再有安全修复。所以你应该确保使用最新的。
最后的安全措施是重新引入更严格的安全性,因此对于本地用户在本地加载字体,您需要包含相关的文件开关。因此本地命令将在 Windows 上:-
wkhtmltopdf --allow "%cd%" --enable-local-file-access WkHTML-IN.htm WkHTML-OUT.pdf
这允许从 windows onts 引用的字体或自定义 local.ttf 字体。
下面的 HTML 加载字体显示了来自 %CD%(下载后的当前目录)的一个示例和一个从 Windows 字体目录引用的示例,仅显示两种方法。
condensed intentionally to just show style lock 'n' load
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title of the document</title>
<style>
@font-face { font-family: 'OpenSans'; font-style: normal; font-weight: normal; src: url("./OpenSans_SemiCondensed-Light.ttf") format("truetype"); }
@font-face { font-family: 'Consolas'; font-style: normal; font-weight: normal; src: url("file:///c:/windows/fonts/consola.ttf") format("truetype"); }
body { font-family: 'OpenSans'; font-weight: 800; }
p { font-family: 'OpenSans'; font-style: italic; font-size: medium; font-weight: 200; }
code, pre { font-family: 'Consolas'; font-size: medium; font-weight: 200; }
</style>
</head><body >
Google fonts cannot generally be used in applications such as WkHtmltox even with a CORS policy etc.<br>
<p>This approach will not work<br>style="font-family: OpenSans;"
<link rel="preconnect" href="https://fonts.googleapis.com"><br>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><br>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet"><br>
<br></p>
What is needed is a local file TTF font as below and the --allow %cd% switch</br>
<code><pre>
@font-face {
font-family: 'OpenSans';
font-style: normal;
font-weight: normal;
src: url("./OpenSans_SemiCondensed-Light.ttf") format("truetype");
}
</pre></code>
Run with <br>
> wkhtmltopdf --allow "%cd%" in.htm out.pdf<br>
or to --allow "C:\Windows\Fonts"<br>
wkhtmltopdf --allow "%cd%" --enable-local-file-access in.htm out.pdf<br>
</body></html>