Search code examples
jqueryajaxdjangoreportlab

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?


Solution

  • 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();