From 6f2a8f006bd3bfa0a261db87abbd46ece5c78381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 14 Jun 2019 15:18:17 -0300 Subject: [PATCH] =?UTF-8?q?Render=5Fto=5Fpdf=20encontrar=20imagens=20em=20?= =?UTF-8?q?STATIC=20ou=20MEDIA=20e=20for=C3=A7ar=20download?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/shortcuts.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/sigi/shortcuts.py b/sigi/shortcuts.py index c70300a..f5f0fff 100644 --- a/sigi/shortcuts.py +++ b/sigi/shortcuts.py @@ -1,21 +1,31 @@ -import cStringIO as StringIO -import os +# -*- coding: utf-8 -*- from cgi import escape +import os -import ho.pisa as pisa from django.conf import settings from django.http import HttpResponse from django.template import Context from django.template.loader import get_template from django.utils.translation import ugettext as _ +import cStringIO as StringIO +import ho.pisa as pisa + def fetch_resources(uri, rel): - path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) + if uri.find(settings.STATIC_URL) != -1: + # Imagem está em STATIC_ROOT + path = os.path.join(settings.STATIC_ROOT, + uri.replace(settings.STATIC_URL, "")) + else: + # Imagem está em MEDIA_ROOT + path = os.path.join(settings.MEDIA_ROOT, + uri.replace(settings.MEDIA_URL, "")) return path def render_to_pdf(template_src, context_dict): + filename = template_src.replace('.html', '').replace('_pdf', '.pdf') template = get_template(template_src) context = Context(context_dict) html = template.render(context) @@ -23,5 +33,7 @@ def render_to_pdf(template_src, context_dict): pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('utf-8')), result, link_callback=fetch_resources) if not pdf.err: - return HttpResponse(result.getvalue(), content_type='application/pdf') + response = HttpResponse(result.getvalue(), content_type='application/pdf') + response['Content-Disposition'] = 'attachment; filename=' + filename + return response return HttpResponse(_(u'We had some errors
%s
') % escape(html))