Bottle framework generate pdf

2019-05-26 06:41发布

I need to generate PDF document using the Bottle framework.

I tried similar to Django but that didn't work:

@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条回答
叛逆
2楼-- · 2019-05-26 07:17

Bottle functions aren't supposed to return the response object, they're supposed to return an iterable (string, list, generator, etc.).

So you want this:

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()
查看更多
登录 后发表回答