使用Python和Matplotlib在服务器端生成.pdf文档
我想写一个服务器端的Python脚本,用来生成.pdf格式的文档。
目前我在服务器上安装了Python 2.7,同时也安装了matplotlib这个库。
我有一个简单的脚本,可以创建一个简单的图表并生成一个.png格式的图片,这个脚本运行得很好。
这是我使用的脚本:
# to access standard output :
import sys
# select a non-GUI backend :
import matplotlib
matplotlib.use('Agg')
#matplotlib.use("cairo.pdf")
#matplotlib.use('PDF')
# import plotting module :
import matplotlib.pyplot as plt
# generate the plot :
plt.plot([1,2,3,2,3,4])
# print the content type (what's the data type)
# the new line is embedded, using '\n' notation :
print "Content-Type: image/png\n"
# print "Content-Type: image/PDF\n"
# print "Content-type: application/pdf"
# output directly to webserver, as a png file:
plt.savefig(sys.stdout, format='png')
# plt.savefig(sys.stdout, format='PDF')
# plt.savefig( "test.pdf", format='pdf' )
我在想,怎么才能做到和之前一样,不过这次是发送一个pdf文件,而不是png图片呢?(#或者加粗的字符是我尝试过的所有内容,放在了注释里)
有人知道吗?
谢谢。
让-克劳德
2 个回答
2
我只是猜测一下,但正确的MIME类型是application/pdf。在那条评论中,你的打印语句里没有包含必要的额外换行符。
4
首先,在你的代码中,你把打印语句里的文字和图形都发送到了标准输出(stdout)。
我刚刚试了你的脚本,把注释改成这样
# plt.savefig(sys.stdout, format='png')
# plt.savefig(sys.stdout, format='PDF')
plt.savefig( "test.pdf", format='pdf' )
然后对我来说运行得很好。我使用的是python 2.6.smth和matplotlib 0.99。