PDF document does not contain utf-8 encoding

Viewed 587

I am making an application on Django. You need to add html page to PDF document. The document is being created, but the Cyrillic alphabet is smeared with squares.

#views.py
def fetch_pdf_resources(uri, rel):
    if uri.find(settings.MEDIA_URL) != -1:
        path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ''))
    elif uri.find(settings.STATIC_URL) != -1:
        path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ''))
    else:
        path = None
    return path


def export_pdf(request, pk):
    obj = get_object_or_404(Application, pk=pk)
    template_path = 'applications/applications_detail.html'
    context = {'applications': obj, 'to_pdf': True}
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="ApplicationDetail.pdf"'

    template = get_template(template_path)
    html = template.render(context)

    pisa_status = pisa.CreatePDF(BytesIO(html.encode('UTF-8')), response, encoding='utf-8', link_callback=fetch_pdf_resources)
    return response


#urls.py
    path('export_pdf/', views.export_pdf, name = 'export_pdf')
1 Answers

This is a common but not a very easy to fix problem. You need to use fonts that support the unicode characters for your PDF document. So, you need two things:

  1. Include some fonts in your django static path (i.e copy them over to 'static/fonts'). I'm using calibri as an example (copied over from windows/fonts).

  2. Use something like the following directive in your html-pdf template:

{% load static %}
@font-face {
    font-family: "Calibri";
    src: url({% static "fonts/calibri.ttf" %});
}
@font-face {
    font-family: "Calibri";
    src: url({% static "fonts/calibrib.ttf" %});
    font-weight: bold;
}
@font-face {
    font-family: "Calibri";
    src: url({% static "fonts/calibrii.ttf" %});
    font-style: italic, oblique;
}
@font-face {
    font-family: "Calibri";
    src: url({% static "fonts/calibriz.ttf" %});
    font-weight: bold;
    font-style: italic, oblique;
}
  1. Set a global style in your html/pdf to use calibri:
*, html {
    font-family: "Calibri";
    font-size:11pt;
    color: red;
}

The above should be enough if the fonts you are using actually support the characters you need and the fonts are found (i.e your static folders work properly) and you are actually overriding te fonts in your css.

For more info, you can take a look at this particular part of my pdf tutorial: https://spapas.github.io/2015/11/27/pdf-in-django/#changing-the-font-to-a-unicode-enabled-one

Related