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.

Revisions

  1. priyadhoundiyal created this gist Oct 9, 2017.
    25 changes: 25 additions & 0 deletions save-pdf.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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'})