Return pdf answer from stdout with Django

I use wkhtmltopdf to create PDF files, however, I don’t know how to return them correctly, so I had to write them to the media folder and then redirect them to the file I just created.

Edit: Ian advises writing to STDOUT, so I changed the wkhtmltopdf command to do this, but now I don't know how to return this content.

I am trying to use subprocess.Popen as follows:

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

But I do not get good results Thank you in advance.

+3
source share
4 answers

You should open your sub command like this:

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 observe:

  • popen'd STDERR, . , communication() Popen.
  • /, , () ().
  • PDF python, .
+4

, genereated.PDF PHP, .

1) pdf STDOUT, , , .

2) MIME . :

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

Chache-Control Expires, .

+1

How do you want them to come back?

If you want them to be 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'm sorry that I didn’t have an answer on how to open a pdf file in a browser, but this is a fragment from a project that I did some time ago, and I forgot some details.

0
source

If you just want to return the PDF as 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')
0
source

Source: https://habr.com/ru/post/1792316/


All Articles