Python 使用reportlab django在表中添加行

Python 使用reportlab django在表中添加行,python,django,postgresql,reportlab,Python,Django,Postgresql,Reportlab,我在django项目中使用reporlab生成pdf。我有多个数据要使用reportlab以表格格式存储。我创建了一个表。但该表只显示第一个数据,表行中没有进一步的数据更新 该表如下所示: 检查|标识|牌照|图像|评论 100 |测试| Qwerty 代码片段如下所示: from django.http import HttpResponse from rest_framework import generics from reportlab.pdfgen import canvas from

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

该表如下所示:

检查|标识|牌照|图像|评论

100 |测试| 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
从django.http导入HttpResponse
从rest_框架导入泛型
从reportlab.pdfgen导入画布
从reportlab.lib.pagesizes导入A4,cm
从reportlab.lib.styles导入getSampleStyleSheet
从reportlab.platypus导入段落、表格、表格样式
从reportlab.lib.enums导入TA_JUSTIFY、TA_LEFT、TA_CENTER
从reportlab.lib导入颜色
类DamageExportViewSet(generics.ListAPIView):
渲染器_类=[PDFRenderer,]
def get(自我,请求):
response=HttpResponse(content\u type='application/pdf')
响应['Content-Disposition']='附件;filename=“损坏报告文件.pdf”'
宽度、高度=A4
styles=getSampleStyleSheet()
styleN=样式[“正文”]
styleN.alignment=TA_左
styleBH=样式[“正常”]
styleBH.alignment=TA_中心
def坐标(x,y,单位=1):
x、 y=x*单位,高度-y*单位
返回x,y
检验=段落(“检验Id”,样式BH)
licplt=段落(“牌照”,样式BH)
imgs=段落(“图像”,样式BH)
cmnts=段落(“注释”,样式BH)
buffer=BytesIO()
p=canvas.canvas(缓冲区,页面大小=A4)
p、 抽绳(20800,“在“+时区.now().strftime(“%b%d,%Y%H:%M:%S”)生成的报告)
damage_data=damage.objects.all()
尝试:
对于损坏中的i\u数据:
检验数据=str(即检验id)。编码('utf-8')
牌照=str(即检查、车辆、牌照)。编码('utf-8')
images=str(i.image).encode('utf-8')
comments=str(i.comment).encode('utf-8')
inspcdata=段落(检验数据,样式)
LNCPL=段落(牌照,样式)
img=段落(图像、样式)
cmt=段落(注释、样式)
数据=[[检验、licplt、imgs、CMNT],
[inspcdata、lncplt、img、cmt]]
除:
通过
表=表(数据,冷宽=[4*cm,4*cm,5*cm,4*cm])
表.setStyle(表样式([
('INNERGRID',(0,0),(-1,-1),0.25,颜色。黑色),
('BOX',(0,0),(-1,-1),0.25,颜色。黑色),
]))
表2.wrapOn(p、宽度、高度)
表2.wrapOn(p、宽度、高度)
表.提款(p,*coord(1.8,9.6,cm))
p、 showPage()
p、 保存()
pdf=buffer.getvalue()
buffer.close()
回应.书面(pdf)
返回响应
我不知道如何在表格中显示损坏模型的所有数据。而图像数据应该作为超链接


提前感谢:)

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

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]
应该是这样:)

而图像数据应该作为超链接

你这是什么意思


干杯

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

(...)

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)
(...)
这将遍历损坏数据查询集并填充表