Search code examples
pythongoogle-app-enginepdfgoogle-cloud-datastorereportlab

How to save generated PDF with Reportlab to Datastore in App Engine Python


I have a method that generates a PDF file using Reportlab library:

def obtenerPDFNuevoPedido(self, handler,rsUsuarioPedido, rsPedido):
    handler.response.headers['Content-Type'] = 'application/pdf'
    handler.response.headers['Content-Disposition'] = 'attachment; filename=output.pdf'
    story = []
    story.append(Paragraph('CHIPAS', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
    story.append(Paragraph('____________ENLANUBE', ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=20)))
    story.append(Spacer(6, 22))
    story.append(Table([[Paragraph(str(strftime("%Y-%m-%d", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_LEFT, fontSize=7)), 
    Paragraph(str(strftime("%H:%M:%S", gmtime())), ParagraphStyle(name="centeredStyle", alignment=TA_RIGHT, fontSize=7))]],colWidths=[5.05 * cm, 3.1 * cm]))
    story.append(Paragraph("DEVELOPED AT ROSHKA-LABS", ParagraphStyle(name="centeredStyle", alignment=TA_CENTER, fontSize=6)))
    story.append(Paragraph('-'*50, styleCentered))
    #...
    #...
    doc = SimpleDocTemplate(handler.response.out, pagesize=letter)
    doc.build(story) 

when I call that method, it opens a save dialog, where I can specify where the file should be saved.

How shoud I do to save the generated pdf file in the Datastore?

Thanks in advance!


Solution

  • 1) You can specify only desired file name (not destination)

    2) Try this (not tested)

    #define your database structure
    from google.appengine.ext import db
    
    class PdfStorage(db.Model): 
       timeAdded = db.DateTimeProperty(auto_now_add=True)
       pdfContent = db.BlobProperty()
    

    Replace your

    doc = SimpleDocTemplate(handler.response.out, pagesize=letter)
    doc.build(story) 
    

    with

    pdf = StringIO()
    
    
    doc = SimpleDocTemplate(pdf, pagesize=letter)
    doc.build(story) 
    
    #get content of generated pdf
    content = pdf.getvalue()
    
    #save to db
    pdfStorage = PdfStorage(pdfContent = content);
    pdfStorage.put()
    
    #output to browser 
    handler.response.write(content)