Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return pdf response from stdout with Django

I am using wkhtmltopdf to create PDF files, how ever I don't know how to return them properly, so I had to write them to my media folder and then redirect to the just created file.

Edit: Ian's advice is to write to STDOUT, so I have changed my wkhtmltopdf command to do that, but now I don't know how to return that content.

I have been trying using subprocess.Popen this way:

r = HttpResponse(Popen(command_args), mimetype='application/pdf')
r['Content-Disposition'] = 'filename=recibos.pdf'
return r

But I am not getting good results Thanks in advance.

like image 734
juanefren Avatar asked Mar 10 '26 04:03

juanefren


1 Answers

You should open your sub command like so:

popen = Popen(command_args, stdout=PIPE, stderr=PIPE)
body_contents = popen.stdout().read()
popen.terminate()
popen.wait()
r = HttpResponse(body_contents, mimetype='application/pdf')

Some things to be careful of:

  1. If your popen'd command writes to STDERR it may deadlock. You can solve this by using the communicate() function on the Popen object.
  2. You should try/finally this to make sure to always terminate() and wait().
  3. This loads the whole PDF into the memory of your python process, you may want to stream the bytes from the command to the outgoing socket.
like image 143
Spike Gronim Avatar answered Mar 11 '26 16:03

Spike Gronim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!