Bottle框架生成pdf

时间:2014-04-05 01:35:40

标签: python bottle reportlab pdflib

我需要使用Bottle框架生成PDF文档。

我尝试过类似于Django,但这不起作用:

@bottle.route('/pd')
def create_pdf():
    response.headers['Content-Type'] = 'application/pdf; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename="test.pdf"'
    from io import BytesIO
    buffer = BytesIO()
    from reportlab.pdfgen import canvas
    p = canvas.Canvas(buffer)
    p.drawString(100,100,'Hello World')
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

1 个答案:

答案 0 :(得分:3)

瓶子函数不应该返回response对象,它们应该返回一个可迭代的(字符串,列表,生成器等)。

所以你想要这个:

from io import BytesIO
from reportlab.pdfgen import canvas

@bottle.route('/pd')
def create_pdf():
    response.headers['Content-Type'] = 'application/pdf; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename="test.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)
    p.drawString(100,100,'Hello World')
    p.showPage()
    p.save()

    return buffer.getvalue()