瓶子框架生成pdf[英] Bottle framework generate pdf

本文是小编为大家收集整理的关于瓶子框架生成pdf的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要使用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

推荐答案

瓶功能不应该返回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()

本文地址:https://www.itbaoku.cn/post/1823874.html

问题描述

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

推荐答案

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