Skip to content

Instantly share code, notes, and snippets.

@priyadhoundiyal
Created October 9, 2017 13:26
Show Gist options
  • Save priyadhoundiyal/4fd69e57245801cc48f837ea3de72e5c to your computer and use it in GitHub Desktop.
Save priyadhoundiyal/4fd69e57245801cc48f837ea3de72e5c to your computer and use it in GitHub Desktop.
generate pdf from template and save to db
from django.template.loader import get_template
from django.template import RequestContext
from django.http import HttpResponse
from django.conf import settings
from weasyprint import HTML, CSS
from django.core.files.uploadedfile import SimpleUploadedFile
@api_view(('GET',))
def savePDF(request, *args, **kwargs):
html_template = get_template('template.html')
# user = request.user
design = Design.objects.first()
rendered_html = html_template.render({'you': design})
pdf_file = HTML(string=rendered_html).write_pdf(
stylesheets=[CSS(settings.STATIC_ROOT + 'css/report.css')])
http_response = HttpResponse(pdf_file, content_type='application/pdf')
http_response['Content-Disposition'] = 'filename="report.pdf"'
design.file = SimpleUploadedFile('Report-'+ design.design_type +'.pdf', pdf_file, content_type='application/pdf')
design.save()
return Response({'saved'})
@MajoRoth
Copy link

MajoRoth commented Oct 2, 2020

Helped me a lot! Thank you sharing your work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment