I have a django app and I would like to create a pdf from my django view. I use weasyprint, and for some reason it doesn't accept my custom font. The font url is working and when I render the same html with the same font-face, I see the correct font, but my pdf is rendered with a wrong one. I also tried the base64 font string, but no luck. My render code is:
import os
from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import get_template
from django.urls import reverse
def render_to_pdf(template_src, context_dict={}):
    font_config = FontConfiguration()
    font_string = '''
        @font-face {
          font-family: 'Titillium Web';
          font-style: normal;
          font-weight: 300;
          src: local('Titillium Web Light'), local('TitilliumWeb-Light'), url('http://X.X.X.X:8000/static/fonts/titillium_web.woff2') format('woff2');
        }
        *, div {font-family: 'Titillium Web';}
    '''
    template = get_template(template_src)
    rendered_html  = template.render(context_dict)
    pdf_file = HTML(string=rendered_html).write_pdf(stylesheets=[
        CSS(settings.BASE_DIR +  '/gui/executive_summary.css'),
        CSS(string=font_string)],font_config=font_config)
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="report.pdf"'
    return response
Any idea what am I doing wrong?
As you can read in documentation:
WeasyPrint should support any font format handled by FreeType (any format widely used except WOFF2)
SRC: http://weasyprint.readthedocs.io/en/latest/features.html#fonts
there are two ways
1) upload font online and paste the link in url.
    eg : @font-face {
        font-family: Gentium;
        src: url(http://example.com/fonts/Gentium.otf);
    }
2) if you want to use font from local directory.
   eg :@font-face{
            font-family: Gothan Narrow;
            src: url(file:///home/javed/Downloads/fonts/GothamNarrow-Light.otf)
        }
If you have @font-face rules in your CSS, you have to create a
FontConfiguration object:
fromweasyprintimport HTML, CSS
from weasyprint.fonts import FontConfiguration
font_config = FontConfiguration()
html = HTML(string='<h1>The title</h1>')
css = CSS(string='''
    @font-face {
        font-family: Gentium;
        src: url(http://example.com/fonts/Gentium.otf);
    }
    h1 { font-family: Gentium }''', font_config=font_config)
html.write_pdf(
    '/tmp/example.pdf', stylesheets=[stylesheet],
    font_config=font_config)
https://weasyprint.readthedocs.io/en/stable/tutorial.html?highlight=FontConfiguration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With