在Python pdfkit中指定字体

问题描述 投票:0回答:2

我在Debian Docker镜像上使用python 3.6和pdfkit 0.6.1(似乎是wkhtmltopdf 0.12.3.2)。我试着查看docswkhtmltopdf options,但没有办法指定整个文档的字体。页脚和标题只有字体选项。

我试过指定

font-family: "Times New Roman", Times, serif;

在我的html div部分的<style>包装中,在html到pdf转换之前,但它没有出现“Times New Roman”。看看二进制文件,它似乎正在使用DejaVuSerif

有没有办法指定要转换的文档的字体?

python pdf-generation wkhtmltopdf pdfkit python-pdfkit
2个回答
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

希望能帮助到你!


0
投票

好吧,看起来我需要安装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中的ttf-liberation,这意味着必须将html样式字体更改为:

font-family: "Times New Roman", Times, "Liberation Serif", serif;
© www.soinside.com 2019 - 2024. All rights reserved.