Search code examples
pythonbottlereportlabpdflib

Bottle framework generate pdf


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

Solution

  • 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()