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.
 
 
 
 

38 lines
1.3 KiB

# -*- coding: utf-8 -*-
from io import BytesIO
from trans import trans
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
# TODO: merge with src/commons/xls/xls_to_response.py => common def
def pdf_to_response(content, filename=None):
"""
Выводит content в django.http.HttpResponse, который и возвращает.
"""
response = HttpResponse(content, content_type='application/pdf')
if filename:
filename = filename.replace('"', "''")
filename = filename.replace('', 'N')
filename = trans(filename)
response['Content-Disposition'] = ('attachment; filename="{}"'.format(filename))
return response
def render_pdf_to_string(request, template_name, dictionary=None):
"""
Рендерит html шаблон в pdf. Возвращает строку,
в которой содержится сгенерированный pdf.
"""
template = get_template(template_name)
html = template.render(Context(dictionary))
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode('utf-8')), result, encoding='utf-8')
pdf_content = result.getvalue()
result.close()
if not pdf.err:
return pdf_content
return None