You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
1.3 KiB
30 lines
1.3 KiB
# -*- coding: utf-8 -*-
|
|
from io import StringIO, BytesIO
|
|
from xhtml2pdf import pisa
|
|
|
|
from django.template.loader import render_to_string
|
|
from django.template import RequestContext
|
|
from django.http import HttpResponse
|
|
|
|
|
|
def pdf_to_response(content, filename=None, filename_encode='windows-1251'):
|
|
"""Выводит content в django.http.HttpResponse, который и возвращает."""
|
|
response = HttpResponse(content, content_type='application/pdf')
|
|
if filename:
|
|
if filename_encode:
|
|
filename = filename.encode(filename_encode)
|
|
response['Content-Disposition'] = ('attachment; filename="%s"' % filename.replace('"', "''"))
|
|
return response
|
|
|
|
|
|
def render_pdf_to_string(request, template_name, dictionary=None):
|
|
"""Рендерит html шаблон в pdf. Возвращает строку, в которой содержится сгенерированный pdf."""
|
|
context_instance = RequestContext(request)
|
|
html = render_to_string(template_name, dictionary, context_instance)
|
|
#return HttpResponse(html) # для отладки
|
|
result = BytesIO()
|
|
pdf = pisa.pisaDocument(BytesIO(html.encode('utf-8')), result)
|
|
pdf_content = result.getvalue()
|
|
if not pdf.err:
|
|
return pdf_content
|
|
return None
|
|
|