return pdf response from stdout with Django

回眸只為那壹抹淺笑 提交于 2019-12-07 14:16:40

问题


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.


回答1:


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.



回答2:


I can't be definitive, because I have only genereated .PDF responses in PHP, however the basic idea will be the same.

1) Write your pdf file to STDOUT, not the file system, just as you would to return any other type of page.

2) Send then with the correct MIME type and headers. These are probaly:

Content-Disposition: inline; filename="MyReportFile.pdf" Content-type: application/pdf

You may need to check out Chache-Control and Expires headers also to get the behaviour you need.




回答3:


How do you want them returned?

If you want them as an attachment you can try:

fname = #something here to give dynamic file names from your variables
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename='+fname
return response

I wish I had the answer for how to open the pdf in browser, but this is a snippet from a project I did a while ago and I forgot some of the details.




回答4:


If you just want to return the pdf as a Django HttpResponse:

from django.http import HttpResponse

def printTestPdf(request):
  return printPdf('/path/to/theFile.pdf')

def printPdf(path):
  with open(path, "rb") as f:
    data = f.read()
  return HttpResponse(data, mimetype='application/pdf')


来源:https://stackoverflow.com/questions/5008466/return-pdf-response-from-stdout-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!