【发布时间】: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