5đź‘Ť
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:
- If your popen’d command writes to STDERR it may deadlock. You can solve this by using the communicate() function on the Popen object.
- You should try/finally this to make sure to always terminate() and wait().
- 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.
1đź‘Ť
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.
- [Django]-How much flexibility is there in a Django for loop?
- [Django]-"error": "invalid_client" django-oauth-toolkit
0đź‘Ť
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.
- [Django]-Why can’t Internet Explorer access my Django Development Server that’s accessible externally (i.e. not on localhost?)
- [Django]-How to modify django-ckeditor inline styles?
- [Django]-Django – Models – Recursively retrieve parents of a leaf node
- [Django]-Saving a Pillow file to S3 with boto
- [Django]-Django: Using 2 different AdminSite instances with different models registered
0đź‘Ť
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')
- [Django]-Django child url does not show its template
- [Django]-Django Rest Framework: DRYer pagination for custom actions
- [Django]-How can I use SearchRank in a Django model field?