pip install xhtml2pdf
Last active
April 9, 2023 16:19
-
-
Save rg3915/69a3fe0208dd549b09f11f8ecc68b5b4 to your computer and use it in GitHub Desktop.
xhtml2pdf print pdf
This file contains hidden or 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
| from io import BytesIO | |
| from django.http import HttpResponse | |
| from django.template.loader import get_template | |
| from xhtml2pdf import pisa | |
| def html_to_pdf(template_src, context_dict={}): | |
| # defining the function to convert an HTML file to a PDF file | |
| template = get_template(template_src) | |
| html = template.render(context_dict) | |
| result = BytesIO() | |
| pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) | |
| if not pdf.err: | |
| return HttpResponse(result.getvalue(), content_type='application/pdf') | |
| return None | |
| def relatorio(request, slug): | |
| template_name = 'relatorio.html' | |
| today = date.today() | |
| instance = get_object_or_404(Modelo, slug=slug) | |
| context = { | |
| 'object': instance, | |
| 'today': today, | |
| } | |
| pdf = html_to_pdf(template_name, context) | |
| response = HttpResponse(pdf, content_type='application/pdf') | |
| filename = f'relatorio_{instance.id}.pdf' | |
| response['Content-Disposition'] = f'inline;filename={filename}' | |
| return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment