1

I am trying to download a pdf file using jquery, ajax & django.

My django views.py:

if request.POST.get('action') == 'download_labels':
    order_list = json.loads(request.POST.get('order_dict'), None)
    PackedOrders(dbname, order_list).downloadLabels()
    file = open('shipping_labels.pdf','rb')
    response = HttpResponse(file, content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename=shipping_labels.pdf"
    os.system('rm shipping_labels.pdf')
    return HttpResponse(response, content_type='application/pdf')

My ajax query:

data : {action:'download_labels',
        order_dict:JSON.stringify($checkedRows)},

success : function(response, status, request) {
    var file = new Blob([response], {type: 'application/pdf'});
    var fileURL = window.URL.createObjectURL(file);
    window.open(fileURL,'_blank');
},

The ajax returns the file as binary data response and open it in a new tab. But all I see in new tab are blank pages. The number of blank pages is equal to number of pages in original pdf file.

In Console I see this:

Error: Invalid XRef stream header
...
Warning: Indexing all PDF objects
pdf.worker.js (line 235)
<System>
PDF 85b859244e496561d60d217869d5d38a [1.3 - / -] (PDF.js: 1.3.76)
Error: Bad FCHECK in flate stream: 120, 239
...

Here is the complete log file.

Manish Gupta
  • 4,438
  • 18
  • 57
  • 104

1 Answers1

0

I'm not a jQuery expert but I do not think jQuery ajax supports blobs. In the documentation it only lists these data types: xml, json, script, or html. However I was able to get this functionality to work without using jQuery and using ajax with plain JavaScript with this code,

My JavaScript (I would also add error handling to this)

var xhr = new XMLHttpRequest();
xhr.open('GET', '/pdf_test', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {
  if (this.status == 200) {
    var blob = new Blob([this.response], {type: 'application/pdf'}),
    fileURL = URL.createObjectURL(blob);
    window.open(fileURL,'_blank');
  }
};

xhr.send();

My django view ( I would also add error handling to this)

def pdf_test(request):
    pdf_file = open(r'C:\Pdfs\calculation_of_semiconductor_failure_rates.pdf', 'rb')
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="shippinglabels.pdf"'
    return response

On top of this if you don't need to open in new tab but can just download the file, then you can avoid ajax/Javascript entirely and just use HTML which is a simpler approach

<a id="pdf-test" href="/pdf_test">Download PDF</a>

For credit and further reading I used these links

jQuery Ajax

StackOverflow question

Introduction to JavaScript Blobs and File Interface

Community
  • 1
  • 1
Josh
  • 2,767
  • 1
  • 27
  • 31