Streaming a PDF with Django

Dear community,

I am finding extremely hard to create a multi-page pdf with few writtens and streaming it.

Each snippet I try is not working for me, so here I am asking for help!

  1. My view is called via a ajax.post call:
$.post( "CreatePDF/", JSON.stringify( data ), "json" )
.done( function ( response )
{
    var pdfWin = window.open("data:application/pdf;base64," + response, '', 'height=650,width=840');
})
  1. Here is the view corresponding to the url:
@user_passes_test(check_user, login_url='no-auth')
def drawYourPDF(request):
    if request.is_ajax():
        if request.method == 'POST':
            # I create my listNames
            return FileResponse( drawPdf( listNames ),
                        as_attachment=True,
                        filename='my_names.pdf')

that calls:

def drawPdf( listNames ):
    buffer = BytesIO()
    p = canvas.Canvas(buffer)

    for i in listNames
        p.drawString( 150 * mm, 1.5 * mm, i.name )
        **# How do I insert a page break so the next name will be in a new page?**

    p.showPage()
    p.save()

    buffer.seek(0)
    return buffer

Any arrangement doesn’t work for me, and I would need to generate on-the-go the PDF, without needing to save into my VPS (it means I also have to act as a garbage collector, I need a specific directory and so on).

This i my result:

Any suggestion, please? :slight_smile:

The first parameter of the window.open call is a url, not the data to be used to populate the data.

If you want to populate that window from this window, you would open the window without any paramters. The return value is the proxy object that you can then use with the window.document.write function to populate that window.
(Note, I’m not sure whether you can do that with pdf data or not - that would be interesting to try.)

You suggestion open a new tab with the content on it, it doesn’t show the pdf.

But guess what?
After hours and hours of attempts I solved in such a way:

        var blob = new Blob([response], {type: 'application/pdf'})
        var dataUri = window.URL.createObjectURL(blob)
        window.open(dataUri, '', 'height=650,width=840')

And it shows the PDF!