Если вы хотите вернуть сгенерированный PDF-файл как http-ответ, у меня работает следующее решение.Я не знаю ваш шаблон.Я использую {{ content.invoid_id }}
, например, для доступа к значениям контекста в шаблоне.
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': 'customer@customer.at',
'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
Нет необходимости во временном файле.Надеюсь, это поможет!
Редактировать: если вам нужны байты файла, вы можете сделать это следующим образом:
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': 'customer@customer.at',
'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())