0

i would like to write a server side python script that generate .pdf documents.

for the moment i have Python 2.7 installed server side and matplolib installed server side too.

A simple script that create a simple plot and generate a .png picture works.

this is the script i use :

# 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'  ) 

I am wondering how to do the same thing but with sending a pdf file instead of a png picture. (the # or bold character are for all the things i tried and put in comment)

Does someone know ?

thanks.

jean-claude

Jouni K. Seppänen
  • 43,139
  • 5
  • 71
  • 100
damiano
  • 1
  • 1
  • 1
  • Can you describe in what way the pdf output failed when you tried it? – Jouni K. Seppänen Oct 02 '10 at 06:16
  • when i use this : plt.savefig(sys.stdout,format='pdf') i get : "the file is damaged and can't be restored" when i use this : plt.savefig(sys.stdout.write('test6.pdf'),format='pdf') i get : file does not start 'with %PDF-' – damiano Oct 02 '10 at 13:35
  • try opening the file with an editor. I'd guess the 1st line would be "Content-Type: image/png" (without quotes), and only then it would go %PDF-etc --- which is how a pdf file should start. – ev-br Oct 02 '10 at 14:02

2 Answers2

4

First of all, in your code you send to stdout both the words from the print statement and the figure itself.

I've just tried your script, changing the comments like this

# plt.savefig(sys.stdout, format='png')
# plt.savefig(sys.stdout, format='PDF')
plt.savefig( "test.pdf", format='pdf'  ) 

and it works just fine for me. I'm using python 2.6.smth and matplolib 0.99

ev-br
  • 24,968
  • 9
  • 65
  • 78
  • it works but only save the .pdf file inside the cgi-bin directory which can't be useful for anything. – damiano Oct 02 '10 at 13:00
  • @damiano: sure, since you didn't specify an explicit path, it saves into a "current" directory. Where do you want to put it, that depends on your needs. – ev-br Oct 02 '10 at 14:00
2

I'm just guessing here, but the correct MIME type is application/pdf, and on that comment line you don't include the necessary extra newline in the print statement.

Community
  • 1
  • 1
Jouni K. Seppänen
  • 43,139
  • 5
  • 71
  • 100