How to connect xhtml2pdf - pisa with the Cyrillic alphabet?

56 Views Asked by At

How to connect xhtml2pdf - pisa with the Cyrillic alphabet? I have a code that generates a PDF document, but if the form fields contain Cyrillic, then black squares are displayed in the PDF document. I read a lot of information on the Internet on how to make friends with the Cyrillic alphabet, but not a single answer saved my situation. I placed a font that supports Cyrillic in the static folder, static/fonts/(font name).ttf. I registered this absolute path according to the instructions. I used call_back, but that didn't help either. Perhaps I'm doing something wrong. Please help! Below is my code, if anyone knows how to fix this situation, please make changes to my code and tell me where my mistake is. I will be very grateful. Thank you in advance!

`def convert_to_pdf(template_name, **context):
    template = get_template(template_name)
    html = template.render(context)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding="UTF-8")
    result.seek(0)
    response = HttpResponse(result.getvalue(), content_type="application/pdf; charset=utf-8")
    response["Content-Disposition"] = 'inline; filename="output.pdf"'

    return response`

The example shows my initial code that generates a PDF document.

1

There are 1 best solutions below

0
bleedcloud On

In html document in style:

@font-face {
font-family: MyFont;
src: url(static/arial/Times_New_Roman.ttf);}

In url your path to rrf. In view:

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, ''))
if uri.find(settings.STATIC_URL) != -1:
    path = os.path.join('static/', uri.replace(settings.STATIC_URL, ''))
else:
    path = None
return path

def create_pdf(request):
template_path = 'pdfs/invoice.html'
phones = []
companies = []

if request.POST['companies'] != '':
    companies = json.loads(request.POST['companies'].replace("'", "\""))

if request.POST['phones'] != '':
    phones = get_list(request.POST['phones'])

print(request.POST['phones'])

context = {
    "companies": companies,
    "phones": phones,
}

response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="report.pdf"'
template = get_template(template_path)
html = template.render(context)

pisaFileObject.getNamedFile = lambda self: self.uri
pisa_status = pisa.CreatePDF(html, dest=response, encoding='UTF-8', link_callback=fetch_pdf_resources)
if pisa_status.err:
   return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response

    

fetch_pdf_resources - function for change path to path with static(from official documentation(maybe not, not sure)). Should work

xhtml2pdf - loading static CSS files and images in Django