6

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?

4

3 回答 3

5

正如您在文档中所读到的:

WeasyPrint 应该支持 FreeType 处理的任何字体格式(除了 WOFF2 之外的任何广泛使用的格式)

SRC:http ://weasyprint.readthedocs.io/en/latest/features.html#fonts

于 2017-12-13T10:19:59.787 回答
3

有两种方法 1) 在线上传字体并将链接粘贴到 url。例如:@font-face { font-family: Gentium; src: url(http://example.com/fonts/Gentium.otf); }

2)如果你想使用本地目录中的字体。例如:@font-face{ font-family: Gothan Narrow; src: url(file:///home/javed/Downloads/fonts/GothamNarrow-Light.otf) }

于 2019-03-13T05:17:27.093 回答
1

如果您@font-face的 CSS 中有规则,则必须创建一个 FontConfiguration对象:

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

于 2018-10-04T05:55:48.167 回答