I'm trying to change the font in my html to pdf project using xhtml2pdf (version 0.2.11) in Django (version 4.2.2). I'm running the project on my Windows 11 Home 22H2, using python 3.11.0
Here is how I try to import the font file html snippet, but the font did not reflect on the page.
html snippet
@font-face {
font-family: Ysabeau Infant;
src: url('fonts/Ysabeau-Infant.ttf');
}
Views.py
def report_rednder_pdf_view(request, *args, **kwargs):
pk = kwargs.get('pk')
report = get_object_or_404(Report, pk=pk)
template_path = 'reports/pdf2.html'
context = {'report': report}
# Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
# If downloadable remove comment
#response['Content-Disposition'] = 'attachment; filename="report.pdf"'
# If viewable remove comment
response['Content-Disposition'] = 'filename="report.pdf"'
# find the template and render it.
template = get_template(template_path)
html = template.render(context)
# create a pdf
pisa_status = pisa.CreatePDF(
html, dest=response)
# if error then show some funny view
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
I tried using the absolute path C:\Users\USER\Desktop\PROJECT\static\fonts\Ysabeau-Infant.ttf instead of the relative path, but that did not work, I get the error:
TTFError
Exception Value: Can't open file "C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf"
and from the terminal I get the error, Permission denied: 'C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf'
I tried running the project as an administrator, and as a user, did not work. Checked the permissions on the temp folder, and checked the permission on the font file.
I tried also the solution from @font-face custom font not rendering properly with xhtml2pdf for django using the function below in the views.py to get the absolute path of the font, but that did not work as well, same error as above:
pisa.CreatePDF(html.encode("UTF-8"), file_object , encoding='UTF-8',
link_callback=fetch_resources)
def fetch_resources(uri, rel):
find_file_in_path_using_uri
return path
I even tried to pass my custom temp folder to the pisa.CreatePDF() function:
temp_dir = tempfile.mkdtemp()
pisa_status = pisa.CreatePDF( html, dest=response, link_callback=fetch_resources, path=temp_dir)
but that did not help, same error as above, no changes occurred at all.
Then I tried using the {% load static %} method, where my html looks like this:
{% load static %}
<html>
<head>
<style>
@page {...}
@font-face {
font-family: 'Ysabeau Infant';
src: url({% static 'fonts/Ysabeau-Infant.ttf' %});
}
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Nothing happened.
Here is the documentation from the xhtml2pdf website: https://xhtml2pdf.readthedocs.io/en/latest/reference.html#using-custom-fonts