当前位置: 首页>>代码示例>>Python>>正文


Python Table._argW[1]方法代码示例

本文整理汇总了Python中reportlab.platypus.Table._argW[1]方法的典型用法代码示例。如果您正苦于以下问题:Python Table._argW[1]方法的具体用法?Python Table._argW[1]怎么用?Python Table._argW[1]使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reportlab.platypus.Table的用法示例。


在下文中一共展示了Table._argW[1]方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: GenerarListaAsistencia

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
  def GenerarListaAsistencia (self,estudiantes,Curso, paralelo):

    namefile = "ListaAsistencia_%s%s.pdf"%(Curso,paralelo)
    doc = SimpleDocTemplate(namefile, pagesize=letter)
    elements = []
    styleSheet = getSampleStyleSheet()

    titulo = Paragraph('''<b>Escuela Particular Dr. Jaime Aspiazu Seminario </b>''',styleSheet["BodyText"])
    stringCurso = u"<b>Curso: %s año básico, Paralelo: %s</b>"%(Curso,paralelo)
    subtitulo = Paragraph(stringCurso,styleSheet["BodyText"])
    fecha = time.strftime("%d/%m/%y")
    stringfecha = "Fecha: %s"%fecha

    datosHeader = [[titulo],[subtitulo],[stringfecha],[]]
    tablaHeader = Table(datosHeader)
    tablaHeader.setStyle(TableStyle([ ('ALIGN',(0,0),(-1,-1),'CENTER'),
                       ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,0),(-1,-1),colors.black),
                       ]))

    #este es la etiqueta de la columna de enumeracion
    N = Paragraph('''<b>N</b><super><font color=black>o</font></super>''', styleSheet["BodyText"])

    datosEstudiante = [[N,u"Nómina Estudiantes", "1","2","3","4","5"]]
    cont =1
    for e in estudiantes:
      aux = []
      aux.append(str(cont))
      aux.append(e)
      aux.append(" ")
      aux.append(" ")
      aux.append(" ")
      aux.append(" ")
      aux.append(" ")
      datosEstudiante.append(aux)
      cont= cont + 1


    tablaEstudiante = Table(datosEstudiante)
    nFila = len(datosEstudiante)
    tablaEstudiante.setStyle(TableStyle([ ('ALIGN',(0,0),(-1,-1),'LEFT'),
                       ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,0),(-1,-1),colors.black),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ('BACKGROUND',(0,0),(0,nFila),colors.beige),
                       ('BACKGROUND',(0,0),(6,0),colors.beige)
                       ]))
    tablaEstudiante._argW[0]=0.5*inch
    tablaEstudiante._argW[1]=3*inch
    tablaEstudiante._argW[2]=0.5*inch
    tablaEstudiante._argW[3]=0.5*inch
    tablaEstudiante._argW[4]=0.5*inch
    tablaEstudiante._argW[5]=0.5*inch
    tablaEstudiante._argW[6]=0.5*inch

    elements.append(tablaHeader)
    elements.append(tablaEstudiante)
    doc.build(elements)
开发者ID:obayona,项目名称:Proyecto-Bases-de-Datos-Python,代码行数:61,代码来源:GeneradorReporte.py

示例2: imprimir

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
    # elements.append(Paragraph("Deuda Inicial: $"+str(ficha.deuda_inicial), style))
    # elements.append(Spacer(1, 0.2 * inch))

    procurador = "Sin información"
    if ficha.procurador:
        procurador = ficha.procurador

    deuda_inicial = 0
    if ficha.deuda_inicial:
        deuda_inicial = ficha.deuda_inicial

    estado = "Sin informacion"
    if ficha.estado:
        estado = ficha.get_estado_display()

    ##elements.append(Paragraph("Procurador: "+ procurador, style))
    ##elements.append(Spacer(1, 0.2 * inch))

    ##elements.append(Paragraph("Estado: "+ficha.get_estado_display(), style))
    ##elements.append(Spacer(1, 0.2 * inch))

    desc_style = ParagraphStyle(name="Normal", fontName="Helvetica", fontSize=9)

    header = [["Nombre:", persona.nombres + " " + persona.apellidos, "Rut:", persona.get_rut()]]
    header.append(["Dirección:", persona.domicilio, "", ""])
    header.append(["Teléfono:", persona.telefono_fijo, "Celular:", persona.telefono_movil])
    header.append(["Rol:", rol, "Carpeta:", carpeta])
    header.append(["Tribunal:", tribunal, "Fecha Asignación:", ficha.fecha_creacion.strftime("%d/%m/%Y")])
    header.append(["Deuda Inicial:", deuda_inicial, "Estado:", estado])

    ts = [
        ("BOX", (0, 0), (-1, -1), 1, colors.grey),
        ("ALIGN", (1, 1), (-1, -1), "LEFT"),
        ("LINEABOVE", (0, 0), (-1, 0), 1, colors.black),
        ("FONT", (0, 0), (0, -1), "Helvetica-Bold"),
        ("FONT", (1, 0), (1, -1), "Helvetica"),
        ("FONT", (0, 0), (0, -1), "Helvetica-Bold"),
        ("FONT", (2, 0), (2, -1), "Helvetica-Bold"),
        ("FONT", (3, 0), (3, -1), "Helvetica"),
        ("SPAN", (1, 1), (-1, 1)),
    ]

    head_table = Table(header, [1.2 * inch, 2.8 * inch, 1.8 * inch, 2.8 * inch])
    head_table.setStyle(ts)
    elements.append(head_table)
    elements.append(Spacer(1, 0.2 * inch))
    data = [["Fecha", "Código", "Descripción", "Receptor"]]

    if eventos:
        for evento in eventos:
            codigo = ""
            if evento.codigo.descripcion:
                codigo = evento.codigo.descripcion

            descripcion = ""
            if evento.descripcion:
                descripcion = evento.descripcion
            receptor = ""
            if evento.receptor:
                receptor = evento.receptor
            data.append(
                [
                    Paragraph(evento.fecha.strftime("%d/%m/%Y"), desc_style),
                    Paragraph(codigo, desc_style),
                    Paragraph(descripcion, desc_style),
                    receptor,
                ]
            )

    ts2 = [
        ("BACKGROUND", (0, 0), (-1, 0), colors.grey),
        # ('BOX',(0,0),(-1,-1),2,colors.grey),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        # ('ALIGN', (1,1), (-1,-1), 'LEFT'),
        # ('LINEABOVE', (0,0), (0,-1), 1, colors.grey),
        ("FONT", (0, 1), (-1, -1), "Helvetica"),
        ("FONT", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), ["#f7f7f7", "#f0f0f0"]),
    ]

    # The bottom row has one line above, and three lines below of
    # various colors and spacing.
    #    ('FONT', (0,-1), (-1,-1), 'Times-Bold')]

    # Create the table with the necessary style, and add it to the
    # elements list.
    table = Table(data, style=ts2)
    table._argW[0] = 0.8 * inch
    table._argW[1] = 3 * inch
    table._argW[2] = 4 * inch
    table._argW[3] = 0.9 * inch
    elements.append(table)
    elements.append(Spacer(1, 0.2 * inch))

    # Write the document to disk
    doc.pagesize = landscape(LETTER)
    doc.build(elements)
    response.write(buffer.getvalue())
    buffer.close()
    return response
开发者ID:henhiskan,项目名称:deudor,代码行数:104,代码来源:views.py

示例3: render_workout_day

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def render_workout_day(day, nr_of_weeks):
    """
    Render a table with reportlab with the contents of the training day
    """

    data = []

    # Init some counters and markers, this will be used after the iteration to
    # set different borders and colours
    day_markers = []
    group_exercise_marker = {}

    # Background colour for days
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(int("73", 16) / 255.0, int("8a", 16) / 255.0, int("5f", 16) / 255.0)

    set_count = 1
    day_markers.append(len(data))

    p = Paragraph(
        u'<para align="center">%(days)s: %(description)s</para>'
        % {"days": day["days_of_week"]["text"], "description": day["obj"].description},
        styleSheet["Bold"],
    )

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_("Date") + " ", "", ""] + [""] * nr_of_weeks)
    data.append([_("Nr."), _("Exercise"), _("Reps")] + [_("Weight")] * nr_of_weeks)

    # Sets
    exercise_start = len(data)
    for set in day["set_list"]:
        group_exercise_marker[set["obj"].id] = {"start": len(data), "end": len(data)}

        # Exercises
        for exercise in set["exercise_list"]:
            group_exercise_marker[set["obj"].id]["end"] = len(data)

            data.append(
                [
                    set_count,
                    Paragraph(exercise["obj"].name, styleSheet["Small"]),
                    Paragraph(exercise["setting_text"], styleSheet["Small"]),
                ]
                + [""] * nr_of_weeks
            )
        set_count += 1

    table_style = [
        ("FONT", (0, 0), (-1, -1), "OpenSans"),
        ("FONTSIZE", (0, 0), (-1, -1), 8),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("LEFTPADDING", (0, 0), (-1, -1), 2),
        ("RIGHTPADDING", (0, 0), (-1, -1), 0),
        ("TOPPADDING", (0, 0), (-1, -1), 3),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 2),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        # Header
        ("BACKGROUND", (0, 0), (-1, 0), header_colour),
        ("BOX", (0, 0), (-1, -1), 1.25, colors.black),
        ("BOX", (0, 1), (-1, -1), 1.25, colors.black),
        ("SPAN", (0, 0), (-1, 0)),
        # Cell with 'date'
        ("SPAN", (0, 1), (2, 1)),
        ("ALIGN", (0, 1), (2, 1), "RIGHT"),
    ]

    # Combine the cells for exercises on the same superset
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]["start"]
        end_marker = group_exercise_marker[marker]["end"]

        table_style.append(("VALIGN", (0, start_marker), (0, end_marker), "MIDDLE"))
        table_style.append(("SPAN", (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(("BACKGROUND", (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        t._argW[0] = 0.6 * cm  # Numbering
        t._argW[1] = 4 * cm  # Exercise
        t._argW[2] = 2 * cm  # Repetitions

    return KeepTogether(t)
开发者ID:boardman,项目名称:wger,代码行数:96,代码来源:helpers.py

示例4: get_assignment

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def get_assignment(assignment, story):
    # title
    story.append(Paragraph(_("Election")+": %s" % assignment.name, stylesheet['Heading1']))
    story.append(Spacer(0,0.5*cm))
    # posts
    cell1a = []
    cell1a.append(Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("Number of available posts"), stylesheet['Bold']))
    cell1b = []
    cell1b.append(Paragraph(str(assignment.posts), stylesheet['Paragraph']))
    # candidates
    cell2a = []
    cell2a.append(Paragraph("<font name='Ubuntu-Bold'>%s:</font><seqreset id='counter'>" % _("Candidates"), stylesheet['Heading4']))
    cell2b = []
    for c in assignment.profile.all():
        cell2b.append(Paragraph("<seq id='counter'/>.&nbsp; %s" % unicode(c), stylesheet['Signaturefield']))
    if assignment.status == "sea":
        for x in range(0,2*assignment.posts):
            cell2b.append(Paragraph("<seq id='counter'/>.&nbsp; __________________________________________",stylesheet['Signaturefield']))
    cell2b.append(Spacer(0,0.2*cm))
    # vote results
    table_votes = []
    results = get_assignment_votes(assignment)
    cell3a = []
    cell3a.append(Paragraph("%s:" % (_("Vote results")), stylesheet['Heading4']))
    if len(results) > 0:
        if len(results[0]) >= 1:
            cell3a.append(Paragraph("%s %s" % (len(results[0][1]), _("ballots")), stylesheet['Normal']))
        if len(results[0][1]) > 0:
            data_votes = []
            # add table head row
            headrow = []
            headrow.append(_("Candidates"))
            for i in range (0,len(results[0][1])):
                headrow.append("%s." %(str(i+1)))
            data_votes.append(headrow)
            # add result rows
            for candidate in results:
                row = []
                if candidate[0][1]:
                    elected = "* "
                else:
                    elected = ""
                c = str(candidate[0][0]).split("(",1)
                if len(c) > 1:
                    row.append(elected+c[0]+"\n"+"("+c[1])
                else:
                    row.append(elected+str(candidate[0][0]))
                for votes in candidate[1]:
                    if type(votes) == type(list()):
                        tmp = _("Y")+": "+str(votes[0])+"\n"
                        tmp += _("N")+": "+str(votes[1])+"\n"
                        tmp += _("A")+": "+str(votes[2])
                        row.append(tmp)
                    else:
                        row.append(str(votes))

                data_votes.append(row)
            polls = []
            for poll in assignment.poll_set.filter(assignment=assignment):
                polls.append(poll)
            # votes invalid
            row = []
            row.append(_("Invalid votes"))
            for p in polls:
                if p.published:
                    row.append(p.votesinvalidf)
            data_votes.append(row)

            # votes cast
            row = []
            row.append(_("Votes cast"))
            for p in polls:
                if p.published:
                    row.append(p.votescastf)
            data_votes.append(row)

            table_votes=Table(data_votes)
            table_votes.setStyle( TableStyle([
                            ('GRID', (0,0), (-1,-1), 0.5, colors.grey),
                            ('VALIGN',(0,0),(-1,-1), 'TOP'),
                            ('LINEABOVE',(0,0),(-1,0),2,colors.black),
                            ('LINEABOVE',(0,1),(-1,1),1,colors.black),
                            ('LINEBELOW',(0,-1),(-1,-1),2,colors.black),
                            ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9))),
                              ]))
    
    # table
    data = []
    data.append([cell1a,cell1b])
    if table_votes:
        data.append([cell3a,table_votes])
        data.append(['','* = '+_('elected')])
    else:
        data.append([cell2a,cell2b])
    data.append([Spacer(0,0.2*cm),''])
    t=Table(data)
    t._argW[0]=4.5*cm
    t._argW[1]=11*cm
    t.setStyle(TableStyle([ ('BOX', (0,0), (-1,-1), 1, colors.black),
                            ('VALIGN', (0,0), (-1,-1), 'TOP'),
#.........这里部分代码省略.........
开发者ID:piratenmv,项目名称:openslides,代码行数:103,代码来源:pdf.py

示例5: render_workout_day

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def render_workout_day(day, nr_of_weeks):
    '''
    Render a table with reportlab with the contents of the training day
    '''

    data = []

    # Init some counters and markers, this will be used after the iteration to
    # set different borders and colours
    day_markers = []
    group_exercise_marker = {}

    # Background colour for days
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(int('73', 16) / 255.0,
                                 int('8a', 16) / 255.0,
                                 int('5f', 16) / 255.0)

    set_count = 1
    day_markers.append(len(data))

    p = Paragraph(u'<para align="center">%(days)s: %(description)s</para>' %
                  {'days': day['days_of_week']['text'],
                   'description': day['obj'].description},
                  styleSheet["Bold"])

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
    data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)

    # Sets
    exercise_start = len(data)
    for set in day['set_list']:
        group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}

        # Exercises
        for exercise in set['exercise_list']:
            group_exercise_marker[set['obj'].id]['end'] = len(data)

            # Process the settings
            if exercise['has_weight']:
                setting_out = []
                for i in exercise['setting_text'].split(u'–'):
                    setting_out.append(Paragraph(i, styleSheet["Small"], bulletText=''))
            else:
                setting_out = Paragraph(exercise['setting_text'], styleSheet["Small"])

            data.append([set_count,
                         Paragraph(exercise['obj'].name, styleSheet["Small"]),
                         setting_out]
                        + [''] * nr_of_weeks)
        set_count += 1

    table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),
                   ('FONTSIZE', (0, 0), (-1, -1), 8),
                   ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                   ('LEFTPADDING', (0, 0), (-1, -1), 2),
                   ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                   ('TOPPADDING', (0, 0), (-1, -1), 3),
                   ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
                   ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

                   # Header
                   ('BACKGROUND', (0, 0), (-1, 0), header_colour),
                   ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
                   ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
                   ('SPAN', (0, 0), (-1, 0)),

                   # Cell with 'date'
                   ('SPAN', (0, 1), (2, 1)),
                   ('ALIGN', (0, 1), (2, 1), 'RIGHT')]

    # Combine the cells for exercises on the same superset
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        t._argW[0] = 0.6 * cm  # Numbering
        t._argW[1] = 4 * cm  # Exercise
        t._argW[2] = 2.5 * cm  # Repetitions

    return KeepTogether(t)
开发者ID:drkarl,项目名称:wger,代码行数:101,代码来源:helpers.py

示例6: workout_log

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
        rowheights[marker - 1] = 5

        # Make the date span 3 cells and align it to the right
        table_style.append(('ALIGN', (0, marker + 1), (2, marker + 1), 'RIGHT'))
        table_style.append(('SPAN', (0, marker + 1), (2, marker + 1)))

    # Combine the cells for exercises on the same set
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows
    for i in exercise_markers:
        counter = 1
        for j in exercise_markers[i]:
            if not j % 2:
                table_style.append(('BACKGROUND', (1, j - 1), (-1, j - 1), colors.lavender))
            counter += 1

    # Make the 'impression' span 3 cells and align it to the right
    for marker in group_day_marker:
        start_marker = group_day_marker[marker]['start']
        end_marker = group_day_marker[marker]['end']

        #table_style.append(('ALIGN', (0, end_marker - 2), (2, end_marker - 2), 'RIGHT'))

        # There is an empty cell between the day blocks, set a border around them
        table_style.append(('INNERGRID',
                            (0, start_marker),
                            (- 1, end_marker - 2),
                            0.25,
                            colors.black))
        table_style.append(('BOX',
                            (0, start_marker),
                            (-1, end_marker - 2),
                            1.25,
                            colors.black))

    # Set the table data
    if data:
        t = Table(data, colwidths, rowheights, style=table_style)

        # Manually set the width of the columns
        for i in range(first_weight_column, nr_of_weeks + first_weight_column):
            t._argW[i] = 1.8 * cm  # Columns for entering the log

        t._argW[0] = 0.6 * cm  # Exercise numbering
        t._argW[1] = 3.5 * cm  # Name of exercise
        t._argW[2] = 1.9 * cm  # Repetitions

    # There is nothing to output
    else:
        t = Paragraph(_('<i>This is an empty workout, what did you expect on the PDF?</i>'),
                      styleSheet["Normal"])

    #
    # Add all elements to the document
    #

    # Set the title (if available)
    if workout.comment:
        P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
                      {'description': workout.comment},
                      styleSheet["Bold"])
        elements.append(P)

        # Filler
        P = Paragraph('<para> </para>', styleSheet["Normal"])
        elements.append(P)

    # Append the table
    elements.append(t)

    # Footer, add filler paragraph
    P = Paragraph('<para> </para>', styleSheet["Normal"])
    elements.append(P)

    # Print date and info
    created = datetime.date.today().strftime("%d.%m.%Y")
    url = reverse('wger.manager.views.workout.view', kwargs={'id': workout.id})
    P = Paragraph('''<para align="left">
                        %(date)s -
                        <a href="%(url)s">%(url)s</a> -
                        %(created)s
                        %(version)s
                    </para>''' %
                  {'date': _("Created on the <b>%s</b>") % created,
                  'created': "wger Workout Manager",
                  'version': get_version(),
                  'url': request.build_absolute_uri(url), },
                  styleSheet["Normal"])
    elements.append(P)

    # write the document and send the response to the browser
    doc.build(elements)

    return response
开发者ID:seraphyn,项目名称:wger,代码行数:104,代码来源:pdf.py

示例7: get_assignment

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
        cell3a.append(Paragraph(
            "%s:" % (_("Vote results")), stylesheet['Heading4']))

        if polls.count() == 1:
            cell3a.append(Paragraph(
                "%s %s" % (polls.count(), _("ballot")), stylesheet['Normal']))
        elif polls.count() > 1:
            cell3a.append(Paragraph(
                "%s %s" % (polls.count(), _("ballots")), stylesheet['Normal']))

        # Add table head row
        headrow = []
        headrow.append(_("Candidates"))
        for poll in polls:
            headrow.append("%s." % poll.get_ballot())
        data_votes.append(headrow)

        # Add result rows
        elected_candidates = list(assignment.elected)
        for candidate, poll_list in vote_results.iteritems():
            row = []

            candidate_string = candidate.clean_name
            if candidate in elected_candidates:
                candidate_string = "* " + candidate_string
            if candidate.name_suffix:
                candidate_string += "\n(%s)" % candidate.name_suffix
            row.append(candidate_string)
            for vote in poll_list:
                if vote is None:
                    row.append('–')
                elif 'Yes' in vote and 'No' in vote and 'Abstain' in vote:
                    row.append(
                        _("Y: %(YES)s\nN: %(NO)s\nA: %(ABSTAIN)s")
                        % {'YES': vote['Yes'], 'NO': vote['No'],
                           'ABSTAIN': vote['Abstain']})
                elif 'Votes' in vote:
                    row.append(vote['Votes'])
                else:
                    pass
            data_votes.append(row)

        # Add valid votes row
        if poll.votesvalid is not None:
            footrow_one = []
            footrow_one.append(_("Valid votes"))
            for poll in polls:
                footrow_one.append(poll.print_votesvalid())
            data_votes.append(footrow_one)

        # Add invalid votes row
        if poll.votesinvalid is not None:
            footrow_two = []
            footrow_two.append(_("Invalid votes"))
            for poll in polls:
                footrow_two.append(poll.print_votesinvalid())
            data_votes.append(footrow_two)

        # Add votes cast row
        if poll.votescast is not None:
            footrow_three = []
            footrow_three.append(_("Votes cast"))
            for poll in polls:
                footrow_three.append(poll.print_votescast())
            data_votes.append(footrow_three)

        table_votes = Table(data_votes)
        table_votes.setStyle(
            TableStyle([
                ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black),
                ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black),
                ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9)))
            ])
        )

        # table
        data = []
        data.append([cell1a, cell1b])
        if polls:
            data.append([cell3a, table_votes])
            data.append(['', '* = ' + _('elected')])
        else:
            data.append([cell2a, cell2b])
        data.append([Spacer(0, 0.2 * cm), ''])
        t = Table(data)
        t._argW[0] = 4.5 * cm
        t._argW[1] = 11 * cm
        t.setStyle(TableStyle([
            ('BOX', (0, 0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        story.append(t)
        story.append(Spacer(0, 1 * cm))

        # text
        story.append(
            Paragraph("%s" % assignment.description.replace('\r\n', '<br/>'),
                      stylesheet['Paragraph']))
开发者ID:DerPate,项目名称:OpenSlides,代码行数:104,代码来源:views.py

示例8: ImprimirVenta

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def ImprimirVenta(request, idventa):
	
	response = HttpResponse(content_type='application/pdf')
	pdf_name = "ventas.pdf" 
	buff = BytesIO()
	
	doc = SimpleDocTemplate(buff,
							pagesize=letter,
							rightMargin=50,
							leftMargin=50,
							topMargin=20,
							bottomMargin=18,
							)
	doc.pagesize = landscape(A5)
	ventas = []
	venta = Venta.objects.get(id = idventa)

	styles = getSampleStyleSheet()
	header = Paragraph("GRUPOEJ - SRL." , getStyleSheet()['Title'])
	documento = Paragraph("DOCUMENTO: "+(str(venta.tipo_documento))+" "+(str(venta.numero_correlativo))+"-"+(str(venta.numero_documento)) , getStyleSheet()['TopicItem1'])
	cliente = Paragraph("CLIENTE / RAZON SOCIAL: "+(str(venta.pedido.cliente.nombres))+" "+(str(venta.pedido.cliente.apellidos))+" - "+(str(venta.pedido.cliente.area)) , getStyleSheet()['TopicItem1'])
	ventas.append(header)
	ventas.append(Spacer(1, 0.2 * inch))
	ventas.append(documento)
	ventas.append(Spacer(1, 0.05 * inch))
	ventas.append(cliente)
	ventas.append(Spacer(1, 0.05 * inch))
	ventas.append(Paragraph(venta.pedido.cliente.tipo_documento+": "+venta.pedido.cliente.nro_documento+" ",getStyleSheet()['TopicItem1']))
	ventas.append(Spacer(1, 0.05 * inch))
	ventas.append(Paragraph("DIRECCION: "+venta.pedido.cliente.direccion+" ",getStyleSheet()['TopicItem1']))
	ventas.append(Spacer(1, 0.05 * inch))
	ventas.append(Paragraph("FECHA DE COMPRA: "+datetime.strftime(venta.fecha, "%d-%m-%Y")+" ",getStyleSheet()['TopicItem1']))
	ventas.append(Spacer(1, 0.1 * inch))
	ventas.append(Paragraph("DETALLE DE LA COMPRA", getStyleSheet()['TopicTitle10']))
	ventas.append(Spacer(1, 0.1 * inch))

	headings = ('DESCRIPCION', 'PRECIO', "CANTIDAD", 'SUBTOTAL')
	detalleventa = [(str(dv.producto.descripcion), str(dv.precio), str(dv.cantidad), str(dv.precio*dv.cantidad)) for dv in DetalleVenta.objects.filter(venta_id=idventa)]
	data = ([headings] + detalleventa)

	data2 = [[Paragraph(cell, getStyleSheet()['TopicItemq0']) for cell in row] for row in data]
	t=Table(data2)
	style = TableStyle(
		[
			('BACKGROUND', (0, 0), (-1, 0), colors.gray),
			('LINEABOVE', (0,0), (-1,0), 2, colors.green),
			('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
			('LINEBELOW', (0,-1), (-1,-1), 2, colors.green),
			('ALIGN', (1,1), (-1,-1), 'CENTER'),
		]
	)

	t.setStyle(style)
	t._argW[0]=4*inch
	t._argW[1]=0.8*inch
	t._argW[2]=0.8*inch
	t._argW[3]=0.8*inch
	ventas.append(t)
	ventas.append(Paragraph("Sub total:__ "+str(venta.sub_total)+" S/", getStyleSheet()['TopicTitle8Right']))
	ventas.append(Paragraph("IGV:___"+str(venta.igv)+" S/", getStyleSheet()['TopicTitle8Right']))
	ventas.append(Paragraph("Total:__ "+str(venta.total)+" S/", getStyleSheet()['TopicTitle8Right']))
	doc.build(ventas)
	response.write(buff.getvalue())
	buff.close()
	return response
开发者ID:xcarlx,项目名称:ventas,代码行数:67,代码来源:views.py

示例9: _create_invoice

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def _create_invoice(invoice_buffer, invoice):
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN + 250, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT -430 , id='EveryPagesFrame',showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 600, id='RemitFrame',showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame,remit_frame], onPage=_create_header)
    

    doc = BaseDocTemplate(invoice_buffer, pageTemplates=[every_page_template], pagesize=A4)
    

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID',(0, 0), (-1, -1),1, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT')
        ])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    data = [
        ['Item','Product', 'Quantity','Unit Price','GST', 'Amount']
    ]
    val = 1
    for item in items:
        data.append(
            [
                val,
                item.description,
                item.quantity,
                '${}'.format(item.line_price_before_discounts_excl_tax),
                '${}'.format(item.line_price_before_discounts_incl_tax-item.line_price_before_discounts_excl_tax),
                '${}'.format(item.line_price_before_discounts_incl_tax)
            ]
        )
        val += 1
    # Discounts
    data.append(
        [
            '',
            '',
            '',
            '',
            '',
            ''
        ]
    )
    for discount in discounts:
        data.append(
            [
                '',
                discount.offer,
                '',
                '',
                '',
                '-${}'.format(discount.amount)
            ]
        )
        val += 1
    t= Table(
            data,
            style=invoice_table_style,
            hAlign='LEFT'
        )
    t._argW[1] = 2.3 * inch
    for x in range (2,6):
        t._argW[x] = 1.2 * inch
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    elements.append(Paragraph('Your application cannot be processed until payment is received.', styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))
    
    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN *1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    
    remittance = Remittance(HEADER_MARGIN,HEADER_MARGIN - 10,invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)
    
    return invoice_buffer
开发者ID:brendanc-dpaw,项目名称:ledger,代码行数:94,代码来源:pdf.py

示例10: render_workout_day

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
        group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}

        # Exercises
        for exercise in set['exercise_list']:
            group_exercise_marker[set['obj'].id]['end'] = len(data)

            # Process the settings
            if exercise['has_weight']:
                setting_out = []
                for i in exercise['setting_text'].split(u'–'):
                    setting_out.append(Paragraph(i, styleSheet["Small"], bulletText=''))
            else:
                setting_out = Paragraph(exercise['setting_text'], styleSheet["Small"])

            # Collect a list of the exercise comments
            item_list = [Paragraph('', styleSheet["Small"])]
            if comments:
                item_list = [ListItem(Paragraph(i, style=styleSheet["ExerciseComments"]))
                             for i in exercise['comment_list']]

            # Add the exercise's main image
            image = Paragraph('', styleSheet["Small"])
            if images:
                if exercise['obj'].main_image:

                    # Make the images somewhat larger when printing only the workout and not
                    # also the columns for weight logs
                    if only_table:
                        image_size = 2
                    else:
                        image_size = 1.5

                    image = Image(exercise['obj'].main_image.image)
                    image.drawHeight = image_size * cm * image.drawHeight / image.drawWidth
                    image.drawWidth = image_size * cm

            # Put the name and images and comments together
            exercise_content = [Paragraph(exercise['obj'].name, styleSheet["Small"]),
                                image,
                                ListFlowable(item_list,
                                             bulletType='bullet',
                                             leftIndent=5,
                                             spaceBefore=7,
                                             bulletOffsetY=-3,
                                             bulletFontSize=3,
                                             start='square')]

            data.append([set_count,
                         exercise_content,
                         setting_out]
                        + [''] * nr_of_weeks)
        set_count += 1

    table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),
                   ('FONTSIZE', (0, 0), (-1, -1), 8),
                   ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                   ('LEFTPADDING', (0, 0), (-1, -1), 2),
                   ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                   ('TOPPADDING', (0, 0), (-1, -1), 3),
                   ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
                   ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

                   # Header
                   ('BACKGROUND', (0, 0), (-1, 0), header_colour),
                   ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
                   ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
                   ('SPAN', (0, 0), (-1, 0)),

                   # Cell with 'date'
                   ('SPAN', (0, 1), (2, 1)),
                   ('ALIGN', (0, 1), (2, 1), 'RIGHT')]

    # Combine the cells for exercises on the same superset
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        if only_table:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 8 * cm  # Exercise
            t._argW[2] = 3.5 * cm  # Repetitions
        else:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 4 * cm  # Exercise
            t._argW[2] = 3 * cm  # Repetitions

    return KeepTogether(t)
开发者ID:DeveloperMal,项目名称:wger,代码行数:104,代码来源:helpers.py

示例11: some_view3

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
    ###############################################################
    #DATUM
    data = [['Datum:', '5/5/2014']]
    a=Table(data,style=[
                        ('BOX',(0,0),(-1,-1),2,colors.black),
                        ('ALIGN',(0,0),(0,0),'CENTER'),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),
                        
    ])
    a._argW[-1]=1.1*inch
     
    elements.append(a)
    elements.append(FrameBreak())

    ###############################################################

    ###############################################################
    #Modell, Ar, Km etc
    data = [['Modell:', serviceprotocol.model],
            ['År:', serviceprotocol.year],
            ['Km:', serviceprotocol.km],
            ['Tekniker:', serviceprotocol.employee],
            ['Regnr:', serviceprotocol.registration_nr]]
    b=Table(data,style=[        #(col, row)
                        ('BOX',(0,0),(-1,-1),2,colors.black),
                        ('LINEABOVE',(0,1),(1,1),1,colors.black),
                        ('LINEABOVE',(0,2),(1,2),1,colors.black),
                        ('LINEABOVE',(0,3),(1,3),1,colors.black),
                        ('LINEABOVE',(0,4),(1,4),1,colors.black),
                        ('ALIGN',(1,0),(1,4),'CENTER'),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),
                        
    ])
    b._argW[1]=1.6*inch

    elements.append(b)
    elements.append(FrameBreak())

    ###############################################################

    ###############################################################
    #Company information

    data = [["Nilsson's MC Shop AB"],
            ['Industrigatan 48'],
            ['58277 Linköping'],
            ['Tel 013-141459'],
            ['Mob. 072-7141471']]

    f=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(0,4),'CENTER'),
                        
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(f)
    elements.append(FrameBreak())

    ###############################################################

    ###############################################################
    #CHECKBOXES
    service_fields = [
                    'oil_check',
                    'motor_check',
开发者ID:Happyhours,项目名称:nmcs-program-OLD,代码行数:70,代码来源:views.py

示例12: generate_assessment_report

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def generate_assessment_report(assess_name, full_marks, module, data, freq, student_list, agg_name):
    filename = assess_name + "_"+module+"_report.pdf"
    fileN = assess_name + "_"+module+"_report"
    logo = os.path.join(os.path.dirname(os.path.abspath(__file__)),"static/reporting/images/cs_header_image.jpg")
    
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+ filename
 
    buffer = BytesIO()
    my_pdf = SimpleDocTemplate(buffer, rightMarging=72, leftMargin=72, topMargin=15, bottomMargin=50)
    
    #container for the pdf elements
    elements = []
    f = Image(logo)
    f.hAlign = 'CENTER'
    f.drawHeight = 1.5*inch
    f.drawWidth = 4 *inch
    elements.append(f)
    
    styles=getSampleStyleSheet()
    styleN = styles["Normal"]
    styleH = styles["Heading1"]
    styleH.alignment = TA_CENTER
    
    elements.append(Paragraph('<h1>'+'Module: '+ module+'</h1>',styleH))
    elements.append(Paragraph('<h3>'+'Assessment: '+ assess_name+'</h3>',styleH))
    if agg_name is not None:
        elements.append(Paragraph('<h3>'+'Aggregator: '+ agg_name+'</h3>',styleH))
    else:
        elements.append(Paragraph('<h3>'+'Aggregator: None '+ '</h3>',styleH))
        
    elements.append(Paragraph('<h3>'+'Full Marks: '+ str(full_marks)+'</h3>',styleH))
    elements.append(Spacer(width=0, height=0.1*cm))
    tdata = [[Paragraph('<b>' + 'Statistics' + '</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,0),1, colors.black),
                                ('BACKGROUND',(0,0),(-1,-1),colors.lightblue)#Give total a grey background)
                              ]))
    table._argW[0]=7.0*inch
    elements.append(table)
    elements.append(Spacer(width=0, height=1*cm))
    
    tdata = [[Paragraph('<b>Class Average</b>',styleN),
              Paragraph('<b>Median</b>',styleN),
              Paragraph('<b>Mode</b>',styleN),
              Paragraph('<b>Standard Deviation</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,-1),1, colors.black)
                              ]))
    table._argW[0]=2.5*inch #Set the size(width) of the first column in the table
    table._argW[1]=1.5*inch
    table._argW[2]=1.5*inch
    table._argW[3]=1.5*inch
    elements.append(table)
    
    tdata = [data[0], data[1], data[2], data[3]],
    table2 = Table(tdata, colWidths=None, rowHeights=None)
    table2.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,-1),1, colors.black)
                              ]))
    #table=Table(tdata, colWidths=80, rowHeights=30)
    table2._argW[0]=2.5*inch #Set the size(width) of the first collumn in the table
    table2._argW[1]=1.5*inch
    table2._argW[2]=1.5*inch
    table2._argW[3]=1.5*inch
    elements.append(table2)
    elements.append(Spacer(width=0, height=1*cm))
    
    tdata = [[Paragraph('<b>' + 'Frequency Analysis' + '</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,0),1, colors.black),
                                ('BACKGROUND',(0,0),(-1,-1),colors.lightblue)#Give total a grey background)
                              ]))
    table._argW[0]=7.0*inch
    elements.append(table)
    elements.append(Spacer(width=0, height=1*cm))
    tdata = [[Paragraph('<b>[0 .. 40)</b>',styleN),
              Paragraph('<b>[40 .. 50)</b>',styleN),
              Paragraph('<b>[50 .. 60)</b>',styleN),
              Paragraph('<b>[60 .. 75)</b>',styleN),
              Paragraph('<b>[75 .. 100]</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,-1),1, colors.black)
                              ]))
    table._argW[0]=1.4*inch #Set the size(width) of the first column in the table
    table._argW[1]=1.4*inch
    table._argW[2]=1.4*inch
    table._argW[3]=1.4*inch
    table._argW[4]=1.4*inch
    elements.append(table)
    
    tdata = [freq[0], freq[1], freq[2], freq[3], freq[4]],
#.........这里部分代码省略.........
开发者ID:fluffels,项目名称:hamster,代码行数:103,代码来源:reporting_api.py

示例13: generate_student_mark_pdf

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def generate_student_mark_pdf(data, student):
    """
    Generates a PDF document with a student's  marks,
    then allowes for it to be downloaded by the student.
    
    Arguments
    Mraks : An associative array of marks for a student
    module : The module the marks are for
    """
    module = data[0]['assessment'][0]
    filename = student + "_" + module + "_marks.pdf"
    print "Location : " + str(os.path.abspath(__file__))
    logo = os.path.join(os.path.dirname(os.path.abspath(__file__)),"static/reporting/images/cs_header_image.jpg")
    
    #Extract student information to paint onto the document
    
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+ filename
    
    buffer = BytesIO()
    
    # Create the PDF object, using the BytesIO object as its "file."
    c = canvas.Canvas(buffer)
    
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    c.setFont("Times-Roman",14,leading=None)
    c.drawString(30,750,"Student : " + student)
    c.drawString(30,725,"Module : " + module)
    
    #Add image on the top right of document
    c.drawImage(logo, 400, 710, width=2.5*inch, height=1.0*inch)
    

    c.line(180,710,380,710)
    
    c.setFont("Helvetica-Bold", 12, leading=None)
    styleN = styles['Normal']
    
    #Get information on the assessment that was clicked
    assessment_clicked = data[0]['assessment'][1][0]
    assessment_clicked_obtained_mark = data[0]['assessment'][1][1]
    assessment_clicked_total_mark = data[0]['assessment'][1][2]
    assessment_clicked_percentage_obtained = '{0:.3}'.format(data[0]['assessment'][1][3])
    
    #create row above the table specifying the assessment clicked
    tdata = [[Paragraph('<b>' + assessment_clicked + '</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,0),1, colors.black)
                              ]))
    table._argW[0]=7.0*inch
    table.wrapOn(c,100, 710)
    table.drawOn(c,50, 600)
    
    tdata = [[Paragraph('<b>Assessment</b>',styleN),
              Paragraph('<b>Final Mark</b>',styleN),
              Paragraph('<b>Mark obtained</b>',styleN),
              Paragraph('<b>Percentage</b>',styleN)
            ]]
    table = Table(tdata, colWidths=None, rowHeights=None)
    table.setStyle(TableStyle([
                                ('GRID',(0,0), (-1,-1),1, colors.black)
                              ]))
    table._argW[0]=2.5*inch #Set the size(width) of the first collumn in the table
    table._argW[1]=1.5*inch
    table._argW[2]=1.5*inch
    table._argW[3]=1.5*inch
    
    #table=Table(tdata, colWidths=80, rowHeights=30)
    table.wrapOn(c,100, 650)
    table.drawOn(c,50,550)
    currPos = 550
    
    
    c.setFont("Helvetica", 11, leading=None)
    
    #Create new table for the marks
    tdata = []
    
    for mark in data[0]['assessment'][2:]:
        assessment_name = mark[0]
        assessment_obtained_mark = mark[1]
        assessment_total_mark = mark[2]
        assessment_percentage_obtained = '{0:.3}'.format(mark[3])
        
        tdata = [assessment_name, assessment_obtained_mark, assessment_total_mark, assessment_percentage_obtained],
        table = Table(tdata, colWidths=None, rowHeights=None)
        table.setStyle(TableStyle([
                                    ('GRID',(0,0), (-1,-1),1, colors.black)
                                  ]))
        #table=Table(tdata, colWidths=80, rowHeights=30)
        table._argW[0]=2.5*inch #Set the size(width) of the first collumn in the table
        table._argW[1]=1.5*inch
        table._argW[2]=1.5*inch
        table._argW[3]=1.5*inch
        table.wrapOn(c,75, 550)
        currPos -= 20
        table.drawOn(c,50, currPos)
#.........这里部分代码省略.........
开发者ID:fluffels,项目名称:hamster,代码行数:103,代码来源:reporting_api.py

示例14: ImprimirReporteEnvacePorProducto

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]
def ImprimirReporteEnvacePorProducto(request, idcliente,idproducto):
	
	response = HttpResponse(content_type='application/pdf')

	pdf_name = "reporte_producto.pdf" 
	buff = BytesIO()

	doc = SimpleDocTemplate(buff,
							pagesize=letter,
							rightMargin=50,
							leftMargin=50,
							topMargin=20,
							bottomMargin=18,
							)
	# doc.pagesize = landscape(A4)
	doc.pagesize = portrait(A4)
	productos = []
	cliente = Cliente.objects.get(id = idcliente)
	# prod = Prestamo.objects.filter(id = idproducto)
	# produc = Producto.objects.filter(id = prod[0].producto.id)
	totales = Prestamo.objects.filter(cliente__id = idcliente, producto__id= idproducto).aggregate(
			total_entregado=Sum(F('entregado'),output_field=FloatField()), 
			total_devuelto=Sum(F('devuelto'),output_field=FloatField())
		)
	# aggregate(total = Sum(F('cantidad')*F('precio'), output_field=FloatField())
	# extra(select = {'total_entregado': 'SUM(entregado)','total_devuelto': 'SUM(devuelto)'})
	styles = getSampleStyleSheet()
	header = Paragraph("GRUPOEJ - SRL." , getStyleSheet()['Title'])
	cli = Paragraph(str(cliente.nombres)+" "+str(cliente.apellidos)+" / "+str(cliente.area)+ " / "+ str(cliente.responsable), getStyleSheet()['TopicTitle8'])
	productos.append(header)
	productos.append(Spacer(1, 0.2 * inch))	
	productos.append(Paragraph("REPORTE TOTAL." , getStyleSheet()['TopicTitle14']))
	productos.append(Spacer(1, 0.05 * inch))
	productos.append(cli)
	productos.append(Paragraph("DETALLE", getStyleSheet()['TopicTitle10']))
	productos.append(Spacer(1, 0.1 * inch))

	headings = ("PRODUCTO","FECHA","NRO DOCUMENTO","ENTREGADA ", 'DEVUELTA', 'DEBE')
	detalleventa = [
			(str(dv.producto.descripcion),str(dv.fecha),str(dv.nro_documento) ,str(dv.entregado), str(dv.devuelto), str(dv.entregado - dv.devuelto)) 
			for dv in Prestamo.objects.filter(cliente__id = idcliente, producto__id= idproducto)]
	data = ([headings] + detalleventa)

	data2 = [[Paragraph(cell, getStyleSheet()['TopicItemq0']) for cell in row] for row in data]
	t=Table(data2)
	style = TableStyle(
		[
			('BACKGROUND', (0, 0), (-1, 0), colors.gray),
			('LINEABOVE', (0,0), (-1,0), 2, colors.green),
			('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
			('LINEBELOW', (0,-1), (-1,-1), 2, colors.green),
			('ALIGN', (1,1), (-1,-1), 'CENTER'),
		]
	)

	t.setStyle(style)
	t._argW[0]=2.5*inch
	t._argW[1]=1.0*inch
	t._argW[2]=1.2*inch
	t._argW[3]=0.9*inch
	t._argW[4]=0.8*inch
	t._argW[5]=0.7*inch
	productos.append(t)
	productos.append(
		Paragraph("Total Entregado &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
			+str(int(totales['total_entregado']))
			+" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
			+"Total Devuelto &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
			+str(int(totales['total_devuelto']))
			+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
			+"TOTAL DEBE: "
			+str(int(totales['total_entregado']) - int(totales['total_devuelto'])), getStyleSheet()['TopicTitle8Right']))
	doc.build(productos)
	response.write(buff.getvalue())
	buff.close()
	return response
开发者ID:xcarlx,项目名称:ventas,代码行数:78,代码来源:views.py

示例15: workout_view

# 需要导入模块: from reportlab.platypus import Table [as 别名]
# 或者: from reportlab.platypus.Table import _argW[1] [as 别名]

#.........这里部分代码省略.........
                   ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ]

    # Set specific styles, e.g. background for title cells
    for marker in day_markers:
        # Set background colour for headings
        table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
        table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))

        # Make the headings span the whole width
        table_style.append(('SPAN', (0, marker), (-1, marker)))

        # Manually set
        rowheights[marker - 1] = 5

    # Combine the cells for exercises on the same set
    counter = 1
    for marker in group_exercise_marker:
        counter += 1
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))
        table_style.append(('BOX',
                            (0, start_marker),
                            (-1, end_marker),
                            0.25,
                            colors.black))

        if counter % 2:
            table_style.append(('BACKGROUND',
                                (0, start_marker),
                                (-1, end_marker),
                                colors.lavender))

    for marker in group_day_marker:
        start_marker = group_day_marker[marker]['start']
        end_marker = group_day_marker[marker]['end']

        table_style.append(('BOX',
                            (0, start_marker),
                            (-1, end_marker - 2),
                            1.25,
                            colors.black))

    # Set the table data
    if data:
        t = Table(data, colwidths, rowheights, style=table_style)

        # Manually set the width of the columns
        if len(t._argW) > 1:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 9 * cm  # Exercise
            t._argW[2] = 4 * cm  # Repetitions

    # There is nothing to output
    else:
        t = Paragraph(_('<i>This is an empty workout, what did you expect on the PDF?</i>'),
                      styleSheet["Normal"])

    #
    # Add all elements to the document
    #

    # Set the title (if available)
    if workout.comment:
        p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
                      {'description': workout.comment},
                      styleSheet["Bold"])
        elements.append(p)

        # Filler
        elements.append(Spacer(10*cm, 0.5*cm))

    # Append the table
    elements.append(t)

    # Footer, date and info
    elements.append(Spacer(10*cm, 0.5*cm))
    created = datetime.date.today().strftime("%d.%m.%Y")
    url = reverse('workout-view', kwargs={'id': workout.id})
    p = Paragraph('''<para align="left">
                        %(date)s -
                        <a href="%(url)s">%(url)s</a> -
                        %(created)s
                        %(version)s
                    </para>''' %
                  {'date': _("Created on the <b>%s</b>") % created,
                   'created': "wger Workout Manager",
                   'version': get_version(),
                   'url': request.build_absolute_uri(url), },
                  styleSheet["Normal"])
    elements.append(p)

    # write the document and send the response to the browser
    doc.build(elements)

    # Create the HttpResponse object with the appropriate PDF headers.
    response['Content-Disposition'] = 'attachment; filename=Workout-{0}-table.pdf'.format(id)
    response['Content-Length'] = len(response.content)
    return response
开发者ID:itsdtr,项目名称:wger,代码行数:104,代码来源:pdf.py


注:本文中的reportlab.platypus.Table._argW[1]方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。