Search code examples
pythonweasyprint

How to use custom font with Weasyprint for non-ascii characters


I have some strings in Japanese that need to be converted to PDF using weasyprint library, for now the japanese characters appear as boxes so I guess it's a matter of fonts, my problem is the code is working perfectly on my local OS, but on Heroku its showing boxes instead, how can I install and use custom font for weasyprint specifically when I don't have access to the system (in my case Heroku)

below is the code I have

from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration

font_config = FontConfiguration()
html = HTML(string='<h1>Title here 自家製フォント工房</h1>')
css = CSS(string='''''', font_config=font_config)

html.write_pdf(
    'report.pdf', stylesheets=[css],
    font_config=font_config)

Solution

  • Found a solution for this by adding the font .ttf file in a folder .fonts this folder will be used by Heoku to look for fonts.

    then in the css i would say

    @font-face {
      font-family: 'Hannari-Regular';
      src: local('Hannari-Regular')
    }
    

    where Hannari-Regular is the name of the font file