Reputation: 326
Trying to build a simple Weasy Print Application with Django
Made a little function at views.py:
def generate_pdf(request):
# Model data
students = Student.objects.all().order_by('last_name')
context = {
'invoice_id': 18001,
'street_name': 'Rue 76',
'postal_code': '3100',
'city': 'Washington',
'customer_name': 'John Cooper',
'customer_mail': '[email protected]',
'amount': 1339.99,
'today': 'Today',
}
# Rendered
html_string = render_to_string('pdf/invoice.html', context)
html = HTML(string=html_string)
result = html.write_pdf()
# Creating http response
response = HttpResponse(content_type='application/pdf;')
response['Content-Disposition'] = 'inline; filename=list_people.pdf'
response['Content-Transfer-Encoding'] = 'binary'
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output = open(output.name, 'r')
response.write(output.read())
return response
After running it I get a UnicodeDecodeError for the line "response.write(output.read())" This is my first time having such a problem, how can I fix that? Thanks!
Upvotes: 2
Views: 1514
Reputation: 326
Fixed it with simple changed 'r' to 'rb':
output = open(output.name, 'rb')
Upvotes: 2
Reputation: 623
If you only want to return the generated PDF as http-response, the following solution is working for me. I don't know your template. I use {{ content.invoid_id }}
for example to access the context values in template.
def generate_pdf(request):
# Model data
students = Student.objects.all().order_by('last_name')
context = {
'invoice_id': 18001,
'street_name': 'Rue 76',
'postal_code': '3100',
'city': 'Washington',
'customer_name': 'John Cooper',
'customer_mail': '[email protected]',
'amount': 1339.99,
'today': 'Today',
}
content = Context()
content.update(context)
template = loader.get_template('yourtemplate.html')
# render and return
html = template.render(context={'content':content}, request=request)
response = HttpResponse(content_type='application/pdf')
HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response)
return response
No need for a temporary file. Hope this helps!
Edit: if you need the file bytes you can do it this way:
def generate_pdf(request):
# Model data
students = Student.objects.all().order_by('last_name')
context = {
'invoice_id': 18001,
'street_name': 'Rue 76',
'postal_code': '3100',
'city': 'Washington',
'customer_name': 'John Cooper',
'customer_mail': '[email protected]',
'amount': 1339.99,
'today': 'Today',
}
content = Context()
content.update(context)
template = loader.get_template('yourtemplate.html')
html = template.render(context={'content':content})
with TemporaryFile() as pdf:
HTML(string=html, base_url=url).write_pdf(pdf)
pdf.seek(0)
# do what every you want with pdf.read())
Upvotes: 0
Reputation: 316
which version of Python do u use? 2.x or 3.x?
Have u tried encode() and import the following module: from __future__ import unicode_literals
Upvotes: 0