带有ReportLab的Python。如何用SimpleDocTemplate写一行?

时间:2013-12-24 15:35:24

标签: python django python-2.7 reportlab django-1.5

我正在使用Python 2.7.6和Django 1.5.5。 我怎么能在SimpleDocTemplate中写一行?

我试试这个:

@login_required
def report(request):
    rep = Report(request.user.username + "_cities.pdf")

    # Title
    rep.add_header("Cities")

    line = Line(0, 100, 500, 100)
    rep.add(line)

    # Body
    columns = ("City")
    cities = [(p.name) for p in City.objects.all()]

    table = Table([columns] + cities, style=GRID_STYLE)
    table.hAlign = "LEFT"
    table.setStyle([('BACKGROUND', (1, 1), (-2, -2), colors.lightgrey)])

    rep.add(table)

    rep.build()
    return rep.response

Line()from reportlab.graphics.shapes import Line。 类Report只是SimpleDocTemplate的包装类:

class Report:
    styles = None
    response = None
    document = None
    elements = []

    def __init__(self, report_file_name):
        self.styles = styles.getSampleStyleSheet()
        self.styles.add(ParagraphStyle(name='Title2',
                                       fontName="Helvetica",
                                       fontSize=12,
                                       leading=14,
                                       spaceBefore=12,
                                       spaceAfter=6,
                                       alignment=TA_CENTER),
                        alias='title2')

        self.response = HttpResponse(mimetype="application/pdf")
        self.response["Content-Disposition"] = "attachment; filename=" + report_file_name

        self.document = SimpleDocTemplate(self.response, topMargin=5, leftMargin=2, rightMargin=1, bottomMargin=1)
        self.document.pagesize = portrait(A4)

        return

    def add_header(self, header_text):
        p = Paragraph(header_text, self.styles['Title2'])
        self.elements.append(p)

    def add(self, paragraph):
        self.elements.append(paragraph)

    def build(self):
        self.document.build(self.elements)

当我调用报告功能时,收到错误消息:

Line instance has no attribute 'getKeepWithNext'

母鸡我使用Line()删除/评论这些行,错误不会发生。

你能帮帮我吗? 怎么写那条线?

1 个答案:

答案 0 :(得分:3)

仅将Line添加到元素列表中不起作用:您只能将Flowable传递给SimpleDocTemplate.build()。但是你可以将它包装在Drawing中,这是一个Flowable

d = Drawing(100, 1)
d.add(Line(0, 0, 100, 0))
rep.add(d)