Skip to content

Instantly share code, notes, and snippets.

@suhailvs
Created March 7, 2019 09:40
Show Gist options
  • Select an option

  • Save suhailvs/56aa0775abb57e5103a2a94e1e751ccd to your computer and use it in GitHub Desktop.

Select an option

Save suhailvs/56aa0775abb57e5103a2a94e1e751ccd to your computer and use it in GitHub Desktop.

python file

class GenerateInvoiceView(APIView):

  def get(self, request, format=None):

    # pdf_file = open(g.get_path(user_id), 'rb')
    html_template = render_to_string('pdf_templates/invoice.html', {'foo': 'bar'})
    # print(html_template)
    pdf_file = HTML(string=html_template).write_pdf()
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=ordersummary.pdf'
    # os.unlink(pdf_file.name) 
    # print(pdf_file.name)
    return response

file --> service.ts

downloadReport(markentryid, student) {
 return this.httpClient.get('/reports/downloadreport/', {
  params: {markentryid: markentryid, student: student},
  headers: new HttpHeaders().append('Content-Type', 'application/pdf'),
  responseType: 'blob',
  observe: 'body'
 });
}

in --> component.ts

downloadPdf() {
 this.studentreportsService.downloadReport(this.id, this.studentid)
 .subscribe(
  res => {
    // http://jslim.net/blog/2018/03/13/Angular-4-download-file-from-server-via-http/
    console.log('start download:', res);
    const url = window.URL.createObjectURL(res);
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = 'progress_report.pdf';
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove(); // remove the element
  }, error => {
    console.log('download error:', JSON.stringify(error));
  }, () => {
    console.log('Completed file download.');
  }
 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment