specify font in Python pdfkit

匿名 (未验证) 提交于 2019-12-03 01:41:02

问题:

I'm using python 3.6 with pdfkit 0.6.1 (and it seems wkhtmltopdf 0.12.3.2) on a Debian Docker image. I tried looking at the docs & wkhtmltopdf options but there's no way to specify the font for the whole document. There are only font options for footers & headers.

I tried specifying

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

In a div wrapper in my html <style> section before html to pdf conversion, but it's not coming up "Times New Roman". Looking into the binary, it seems it's using DejaVuSerif.

Is there a way to specify the font for the document being converted?

回答1:

I have managed to customize the font of my entire document passing a CSS stylesheet using user-style-sheet. Inside your CSS file, in order to avoid issues with the font structure, I recommend you to convert the font to a base64 format. 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; } 

You can use a tool like this to transform your font to base64.

Hope it helps!



回答2:

Well, looks like I need to install ttf-mscorefonts-installer, but first, I need to add contrib into my sources.list

sed -Ei 's/main$/main contrib/' /etc/apt/sources.list 

Then install the package

apt-get -y install ttf-mscorefonts-installer 

The closest free font I was able to find was Liberation Serif in ttf-liberation, which means the html style font had to be changed to:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!