serve a stringIO (pdf) as download python

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/htmlrnrn"
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


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.

链接地址: http://www.djcxy.com/p/46720.html

上一篇: 在原子编辑器中导入matplotlib.pyplot

下一篇: 以下载python的形式提供stringIO(pdf)