1

I have a cgi python script which saves a matplotlib generated picture as pdf to stringIO and as png to stringIO. The png picture will be shown on a new page which works well.

sio = cStringIO.StringIO()
pylab.savefig(sio, format='pdf')
sio.close()

sio =cStringIO.StringIO()
print "Content-type:text/html\r\n\r\n"
pylab.savefig(sio, format='png', bbox_inches='tight')
print "<html>"
...
print "<img id='Plot' src='data:image/png;base64,%s'/>" % sio.getvalue().encode('base64').strip()
...

Is there a way to serve the pdf in StringIO as download. I know there are examples for http download headers, when the file is located on the server.

print "Content-Type:application/download; name=\"filename\"";
print "Content-Disposition: attachment; filename=\"filename\"";
print

f=open("filename", "rb")
str = f.read();
print str
f.close()

So I guess I will need a second cgi-script for the download. But I don't know how to pass the stringIO to make it downloadable as pdf without saving it on the server.

Thanks for help

AvidLearner
  • 4,123
  • 5
  • 35
  • 48
Dukaaza
  • 47
  • 1
  • 8
  • Why can't you respond with it directly, instead of trying to generate HTML? – Ignacio Vazquez-Abrams Jun 04 '15 at 16:57
  • when the form is submitted, I want the user to see the picture on a new html page and give him the ability to save this image as pdf on his harddrive – Dukaaza Jun 04 '15 at 17:01
  • The example you have for the cgi png is incomplete actually since you dont actually print the png. – Pykler Jun 04 '15 at 17:04
  • i didnt print the rest of the code, cause showing the png in a new html is not the core of my problem. This part works. – Dukaaza Jun 04 '15 at 17:06

1 Answers1

1

Same exact way you are serving your png should work (if your example was complete). Here is the second snippet you sent modified to fit your example:

fn = 'mydownload.pdf'
print 'Content-Type:application/pdf';
print 'Content-Disposition: attachment; filename="%s"' %(fn);
print
print sio.getvalue()

if you are using wsgi instead of cgi, you can write straight to the stream.

Pykler
  • 14,565
  • 9
  • 41
  • 50
  • and what do i write in the header for filename? – Dukaaza Jun 04 '15 at 17:09
  • PS. @Dukaaza I would suggest you have a look at bottle or django, will make your life easier on the long run. See http://stackoverflow.com/a/22875961/742390 – Pykler Jun 04 '15 at 17:13
  • nice your example works well, thank you. I have heard of Django but i can't use i have not the rights to install it on server. – Dukaaza Jun 04 '15 at 17:28
  • Thanks @Dukaaza feel free to mark this question as answered then. – Pykler Jun 04 '15 at 17:29