如何使用Reportlab将生成的PDF保存到App Engine Python的Datastore?

7
我有一个使用Reportlab库生成PDF文件的方法:
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) 

当我调用那个方法时,它会打开一个保存对话框,在那里我可以指定文件保存的位置。

我应该如何将生成的PDF文件保存在数据存储中?

谢谢!

1个回答

8

1) 您只需指定所需的文件名(而非目标路径)。

2) 请尝试以下方法(未经测试):

#define your database structure
from google.appengine.ext import db

class PdfStorage(db.Model): 
   timeAdded = db.DateTimeProperty(auto_now_add=True)
   pdfContent = db.BlobProperty()

请替换你的
doc = SimpleDocTemplate(handler.response.out, pagesize=letter)
doc.build(story) 

使用

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)

1
谢谢你russenreaktor!我编辑了你回答的两行代码=),现在它完美地工作了! - Lucas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接