Created
November 8, 2017 23:57
-
-
Save dvl/1cb17ce15ce4b4e5f1cff14639a6f69b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import weasyprint | |
from django.template.response import TemplateResponse | |
class PDFResponse(TemplateResponse): | |
def __init__(self, *args, **kwargs): | |
filename = kwargs.pop('filename', None) | |
super().__init__(*args, **kwargs) | |
self['Content-Disposition'] = 'attachment; filename={}'.format(filename) | |
self['Content-Type'] = 'application/pdf' | |
@property | |
def rendered_content(self): | |
template = self.resolve_template(self.template_name) | |
context = self.resolve_context(self.context_data) | |
rendered_html = template.render(context) | |
pdf = self.content_processor(rendered_html) | |
return pdf | |
def content_processor(self, content): | |
""" Define como o HTML deve ser transformado em PDF """ | |
output = io.StringIO() | |
pdf = weasyprint.HTML(string=content) | |
pdf.write_pdf(target=output) | |
return output.getvalue() | |
class PDFView: | |
filename = 'output.pdf' | |
response_class = PDFResponse | |
def get_filename(self): | |
return self.filename | |
def render_to_response(self, context, **response_kwargs): | |
response_kwargs.update({ | |
'filename': self.get_filename() | |
}) | |
return super().render_to_response(context, **response_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment