【问题标题】:How to make a simple table in ReportLab如何在 ReportLab 中制作一个简单的表格
【发布时间】:2011-03-23 07:42:01
【问题描述】:

如何在 ReportLab 中制作简单的表格?我需要制作一个简单的 2x20 表并输入一些数据。有人可以给我举个例子吗?

【问题讨论】:

    标签: python pdf pdf-generation


    【解决方案1】:

    最简单的表格函数:

    table = Table(data, colWidths=270, rowHeights=79)
    

    有多少列和结束行取决于数据元组。我们所有的表函数看起来像:

    from reportlab.platypus import SimpleDocTemplate
    from reportlab.platypus.tables import Table
    cm = 2.54
    
    def print_pdf(modeladmin, request, queryset):
        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
    
        elements = []
    
        doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
    
        data=[(1,2),(3,4)]
        table = Table(data, colWidths=270, rowHeights=79)
        elements.append(table)
        doc.build(elements) 
        return response
    

    这将使表格成为 2X2,并用数字 1、2、3、4 填充它。然后你可以制作文件文件。在我的情况下,我制作了 HttpResponse,它与文件非常相似。

    【讨论】:

    • 对我来说,它可以很好地创建表格,但表格的填充有点相反,所以表格看起来第 1 行:3 4 第 2 行:1 2
    【解决方案2】:

    只是对 radtek 和 Pol 答案的补充:

    您可以将 SimpleDocTemplate() 的 response 参数替换为像 io.BytesIO() 这样的缓冲区对象,如下所示:

    from reportlab.platypus import SimpleDocTemplate
    from reportlab.platypus.tables import Table
    import io
    
    cm = 2.54
    buffer = io.BytesIO()
    doc = SimpleDocTemplate(buffer, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
    ... # To be continued below
    

    当您想将 PDF 对象转换为字节,然后转换为字节字符串以 JSON 格式发送时,这可能很有用:

    ... # Continuation from above code
    buffer.seek(0)
    buffer_decoded = io.TextIOWrapper(buffer, encoding='utf-8', errors='ignore').read()
    
    return JsonResponse({
        "pdf_bytes": buffer_decoded,
    })
    

    取自文档 (https://www.reportlab.com/docs/reportlab-userguide.pdf):

    The required filename can be a string, the name of a file to receive the created PDF document; alternatively it can be an object which has a write method such as aBytesIO or file or socket
    

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 2011-01-02
      • 2012-08-02
      相关资源
      最近更新 更多