【问题标题】:Add rows in a table using reportlab django使用reportlab django在表格中添加行
【发布时间】:2017-08-10 05:09:26
【问题描述】:

我正在使用 reporlab 在我的 django 项目中生成 pdf。我有多个数据要使用reportlab 以表格格式存储。我创建一个表。但该表仅显示第一个数据,在表行中没有进一步的数据更新。

表格如下:

Inspection_Id |牌照_牌照 |图片 |评论

100 |测试 | http://www.test.com/image.jpg | Qwerty

代码片段如下:

from django.http import HttpResponse
from rest_framework import generics
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, cm 
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER 
from reportlab.lib import colors

class DamageExportViewSet(generics.ListAPIView):

renderer_classes = [PDFRenderer,]

def get(self, request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Damage Report File.pdf"'
    width, height = A4
    styles = getSampleStyleSheet()
    styleN = styles["BodyText"]
    styleN.alignment = TA_LEFT
    styleBH = styles["Normal"]
    styleBH.alignment = TA_CENTER

    def coord(x, y, unit=1):
        x, y = x * unit, height - y * unit
        return x, y

    inspection = Paragraph('''<b>Inspection Id</b>''', styleBH)
    licplt = Paragraph('''<b>Licence Plate</b>''', styleBH)
    imgs = Paragraph('''<b>Images</b>''', styleBH)
    cmnts = Paragraph('''<b>Comments</b>''', styleBH)

    buffer = BytesIO()

    p = canvas.Canvas(buffer, pagesize=A4)

    p.drawString(20, 800, "Report generated at " + timezone.now().strftime('%b %d, %Y %H:%M:%S'))

    damage_data = Damage.objects.all()
    try:
        for i in damage_data:
            inspection_data = str(i.inspection_id).encode('utf-8')
            licence_plate = str(i.inspection.vehicle.licence_plate).encode('utf-8')
            images = str(i.image).encode('utf-8')
            comments = str(i.comment).encode('utf-8')
            inspcdata = Paragraph(inspection_data, styleN)
            lncplt = Paragraph(licence_plate, styleN)
            img = Paragraph(images, styleN)
            cmt = Paragraph(comments, styleN)
            data = [[inspection, licplt, imgs, cmnts],
                    [inspcdata, lncplt, img, cmt]]

    except:
        pass
    table = Table(data, colWidths=[4 * cm, 4 * cm, 5 * cm, 4 * cm])

    table.setStyle(TableStyle([
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ]))
    table.wrapOn(p, width, height)
    table.wrapOn(p, width, height)
    table.drawOn(p, *coord(1.8, 9.6, cm))
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

我不明白如何在表格中显示来自 Damage 模型的所有数据。并且图像数据应该作为超链接。

在此先感谢 :)

【问题讨论】:

    标签: python django postgresql reportlab


    【解决方案1】:

    您将在每个循环步骤中覆盖 data 数组。 你需要它是这样的:

    data=[
        ["Inspection_Id", "Licence_Plate", "Images", "Comment"],
        ["100", "TEST", "http://url.to/png", "Qwerty"],
        ["200", "2nd data row", "http://url.to/gif", "Dvorak"]
    ]
    

    这样你就可以得到类似的东西

    | Inspection_Id | Licence_Plate | Images            | Comment |
    | ------------- |-------------- | ----------------- | ------- |
    | 100           | TEST          | http://url.to/png | Qwerty  |
    | 200           | 2nd data row  | http://url.to/gif | Dvorak  |
    

    因此,您的循环需要如下所示:

    # Fill the first row of `data` with the heading, only once!
    data = [[inspection, licplt, imgs, cmnts]]
    try:
        for i in damage_data:
            inspection_data = str(i.inspection_id).encode('utf-8')
            licence_plate = str(i.inspection.vehicle.licence_plate).encode('utf-8')
            images = str(i.image).encode('utf-8')
            comments = str(i.comment).encode('utf-8')
            inspcdata = Paragraph(inspection_data, styleN)
            lncplt = Paragraph(licence_plate, styleN)
            img = Paragraph(images, styleN)
            cmt = Paragraph(comments, styleN)
    
            # Add this loop's step row into data array
            data += [inspcdata, lncplt, img, cmt]
    

    应该就是这样:)

    并且图像数据应该作为超链接。

    这是什么意思?

    干杯!

    【讨论】:

      【解决方案2】:

      如果您的主要目标是迭代并在表中显示 damage_data 记录,请尝试以下操作:

      (...)
      
      damage_data = Damage.objects.all()
      data = []
      data.append(["Inspection_Id", "License_Plate", "Images", "Comment"])
      try:
          for i in damage_data:
              row = []
              inspection_data = str(i.inspection_id).encode('utf-8')
              licence_plate = str(i.inspection.vehicle.licence_plate).encode('utf-8')
              images = str(i.image).encode('utf-8')
              comments = str(i.comment).encode('utf-8')
              row.append(inspection_data)
              row.append(license_plate)
              row.append(images)
              row.append(comments)
              data.append(row)
      (...)
      

      这应该遍历您的 damage_data 查询集并填充您的表。

      【讨论】:

        猜你喜欢
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 2017-01-14
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 2018-11-25
        • 1970-01-01
        相关资源
        最近更新 更多