lustdante
lustdante

Reputation: 493

Opening PDF file generated by Reportlab in Django using Ajax

I'm using Reportlab with Django to generate pdf of data computed on the client side.

Ajax is chosen because the client has non-trivial data to transfer for pdf generation.

$.ajax({
    type:'POST',
    url:document.URL + '/export',
    data: JSON.stringify(data),
    dataType:'json',
    contentType:'application/pdf',
    success:function(data){
        // Question 1. What should I insert here to download pdf?
    },
    error:function(e){
        ...
    }
});

And here is the view.py

def export(request, *args, **kwargs):

    // Perform Ajax check
    ...

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="essay.pdf"'

    p = canvas.Canvas(response, bottomup=0)
    data = json.loads(request.body)

    p.drawString(100, 100, "Hello world.")
    p.showPage()
    p.save()
    return response

Question 2. I could not get ajax to succeed with its request, only invoking error callback. The same issue was referred in this question

ReportLab in Django

but it wasn't answered. Am I missing something?

Upvotes: 2

Views: 2151

Answers (2)

Claude Vedovini
Claude Vedovini

Reputation: 2481

my solution would be to use a standard form instead of ajax.

You can put a form in your html (or build it using JS)

<form id="my_form" action="export" method="post">
    <input id="my_form_data" type="hidden" name="data" />
</form>

Then, when you want your data sent, using JS:

$('#my_form_data').value(JSON.stringify(data));
$('#my_form').submit();

Upvotes: 1

Dragos C
Dragos C

Reputation: 363

You can't download a file via ajax. But you can use this library: jquery.fileDownload.

jQuery File Download is a cross server platform compatible jQuery plugin that allows for an Ajax-like file download experience that isn’t normally possible using the web.

Upvotes: 1

Related Questions