0

while converting Hindi words in HTML to pdf by using the xhtml2pdf library in Django projects I am getting some coded words on how to convert in the correct way?

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, encoding='UTF-8')
  if not pdf.err:
      return HttpResponse(result.getvalue(), content_type='application/pdf')
  return None

pdf image

Abhi
  • 67
  • 7

1 Answers1

1

This seems to be an encoding issue. To test this, you can render the template with Django:

def render_to_pdf(template_src, context_dict={}):
  template = get_template(template_src)
  html  = template.render(context_dict)

  return HttpResponse(html)

and convert manually to PDF by opening the Django URL with the xhtml2pdf command line utility:

xhtml2pdf -s http://127.0.0.1:8000/quarter_notification_pdf/

If this produces a legible PDF file, the issue is with your code. Here is the official xhtml2pdf documentation on how to use it with Django: https://xhtml2pdf.readthedocs.io/en/latest/usage.html#using-xhtml2pdf-in-django . They use the CreatePDF() function.

Another answer dealing with xhtml2pdf: https://stackoverflow.com/a/7584674/4613449

For some alternatives: How to convert webpage into PDF by using Python

Sivasankaran K B
  • 322
  • 3
  • 10