【问题标题】:specify font in Python pdfkit在 Python pdfkit 中指定字体
【发布时间】:2018-07-12 22:18:48
【问题描述】:
我在 Debian Docker 映像上使用 python 3.6 和 pdfkit 0.6.1(似乎是 wkhtmltopdf 0.12.3.2)。我尝试查看docs 和wkhtmltopdf options,但无法为整个文档指定字体。页脚和页眉只有字体选项。
我尝试指定
font-family: "Times New Roman", Times, serif;
在 html 到 pdf 转换之前,在我的 html <style> 部分的 div 包装器中,但它没有出现“Times New Roman”。查看二进制文件,它似乎正在使用DejaVuSerif。
有没有办法为要转换的文档指定字体?
【问题讨论】:
标签:
python
pdf-generation
wkhtmltopdf
pdfkit
python-pdfkit
【解决方案1】:
我已经设法自定义整个文档的字体,并使用user-style-sheet 传递 CSS 样式表。在您的 CSS 文件中,为了避免字体结构出现问题,我建议您将字体转换为 base64 格式。 base64 reference
@font-face {
font-family: 'YourFont';
font-style: normal;
font-weight: 400;
src: url(data:font/opentype;charset=utf-8;base64,d09GRgABAAAAAD00AA4A---[large string ommited]----3MAuAH/hbAEjQA=) format("woff"),
url(data:font/truetype;charset=utf-8;base64,AAEAAAARAQAABAAQRFNJRwAAAAEAAJUIAAA---[large string ommited]-----wAAAAAAAAAAAAEAAAAA) format("truetype");
}
* {
font-family: "YourFont" !important;
}
您可以使用this 之类的工具将字体转换为base64。
希望对你有帮助!
【解决方案2】:
好吧,看来我需要安装ttf-mscorefonts-installer,但首先,我需要将contrib 添加到我的sources.list 中
sed -Ei 's/main$/main contrib/' /etc/apt/sources.list
然后安装包
apt-get -y install ttf-mscorefonts-installer
我能找到的最接近的免费字体是Liberation Serif in ttf-liberation,这意味着必须将html样式字体更改为:
font-family: "Times New Roman", Times, "Liberation Serif", serif;