Search code examples
pythongoogle-app-enginepdfreportlab

User downloadable PDFs in Google App Engine returning corrupted PDFs


I've created a python script that generates a PDF from supplied user data using reportlab. The PDFs download fine and everything works when I run the script from the command line. However when I try to pass the file to Google App Engine like this:

...

outputstream = StringIO.StringIO()
PDF = output.write(outputstream)

class PDFHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'attachment; filename=Myfile.pdf'
        self.response.headers['Content-Transfer-Encoding'] = 'binary'
        self.response.out.write(PDF)

and run the development server, the PDF downloads, but when I try to open it, chrome says it can't open the file, Ubuntu's document viewer says "can't open plain/text document", even though when I check the document's properties it states 'application/pdf' and it has the appropriate .pdf suffix, and when I try to open it in GIMP image viewer, it states "document is damaged." Is there something wrong with the way I'm passing the file to the webapp2 handler? Any help would be greatly appreciated!


Solution

  • I solved the problem by going over some old tutorials. It was in the last line of code where I had neglected to include .getvalue() to the output:

    outputstream = StringIO.StringIO()
    PDF = output.write(outputstream)
    
    class PDFHandler(webapp2.RequestHandler):
        def get(self):
            self.response.headers['Content-Type'] = 'application/pdf'
            self.response.headers['Content-Disposition'] = 'attachment; filename=Myfile.pdf'
            self.response.headers['Content-Transfer-Encoding'] = 'binary'
            self.response.out.write(PDF.getvalue())