[Fixed]-Generate pdf files with Weasyprint, save in zip file, send that zip file to client and present it for download

1👍

A slightly different approach would be to move the zip file to a public directory and then send that location to the client (e.g. json formatted), i.e.:

publicPath = os.path.join('public/', os.path.basename(zipPath))
os.rename(zipPath, os.path.join('/var/www/', publicPath))

jsonResp = '{ "zip-location": "' + publicPath + '" }'

resp = HttpResponse(jsonResp, content_type = 'application/json');

Then in your client’s javascript:

var res = JSON.parse(response);
var zipFileUrl = '/' + res['zip-location'];

window.open(zipFileUrl, '_blank');

'/' + res['zip-location'] assumes that your page lives in the same folder as the public directory (so http://example.com/public/pdf-files-123.zip points to /var/www/public/pdf-files-123.zip on your file system).

You can clean up the public directory with a cron job that deletes all the .zip files in there that are older than an hour or so.

0👍

Once you have exited the with block the filehandle is closed. You should reopen the file (this time with open) and use read() to pass the contents to HttpResponse instead of passing the filehandle itself.

with zipfile.ZipFile(zipPath, 'w') as myzip
    for f in lstFileNames:
        myzip.write(f)
with open(zipPath, 'r') as myzip:
    return HttpResponse(myzip.read(), content_type = "application/x-zip-compressed")

If that works, then you can use a StringIO instance instead of a filehandle to store the zip file. I’m not familiar with Weasyprint so I don’t know whether you can use StringIO for that.

Leave a comment