Проблема кодировки xhtml2pdf не работает с кириллицей выводит вместо букв квадраты
html:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{report_id}}</title>
<style>
@font-face { font-family: Arial; src: url("/static/fonts/arial.ttf"); }
body{
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>This is the report page for {{name}}.You can download it in PDF format.</h1>
<p>Этот текст написан на кириллице</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta debitis libero non porro aperiam inventore cumque delectus molestias, explicabo consequatur obcaecati sit harum repudiandae exercitationem, impedit veritatis iste nesciunt praesentium.</p>
<h1> The amount is {{amount}}</h1>
<h1> The ID is {{id}}</h1>
</body>
</html>
utils.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 render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
views.py:
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
employee_ = Employee.objects.get(id=1)
employee_name = employee_.name
data = {
"name": employee_name, #you can feach the data from database
"id": 18,
"amount": 333,
}
pdf = render_pdf('pdf/report.html', data)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "Report_for_%s.pdf" %(data['id'])
content = "inline; filename= %s" %(filename)
response['Content-Disposition'] = content
return response
return HttpResponse("Page Not Found")