Пример #1
0
def generate_donation_receipt(member, year):
    fees = member.fee_payments.filter(value_datetime__year=year).aggregate(
        fees=models.Sum('amount'))['fees'] or Decimal('0.00')
    donations = member.donations.filter(value_datetime__year=year).aggregate(
        donations=models.Sum('amount'))['donations'] or Decimal('0.00')
    address = member.address
    if (donations + fees) <= 0:
        raise Exception(f'No donations or fees for {year}.')

    story = []
    _buffer = BytesIO()
    local_settings = GemeinnuetzigkeitConfiguration.get_solo()
    global_settings = Configuration.get_solo()
    doc = get_default_document(_buffer)
    style = get_paragraph_style()

    # Header
    our_address = '\n'.join([global_settings.name,
                             global_settings.address]).replace('\n', '<br />')
    our_address = Paragraph(our_address, style['Normal'])
    our_title = Paragraph('Aussteller (Steuerbegünstigte Einrichtung)',
                          style['Heading5'])
    story.append(
        Table(
            [[
                our_title,
            ], [
                our_address,
            ]],
            colWidths=[doc.width * 1],
            hAlign='LEFT',
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 1), 0.5, colors.black),
            ]),
        ))
    story.append(
        Paragraph('Bestätigung über Geldzuwendungen/Mitgliedsbeitrag',
                  style['Heading3']))
    story.append(
        Paragraph(
            'im Sinne des § 10b des Einkommenssteuergesetzes an eine der in § 5 Abs. 1 Nr. 9 des Körperschaftssteuergesetzes bezeichneten Körperschaften, Personenvereinigungen oder Vermögensmassen',
            style['Normal']))
    story.append(Spacer(1, 5 * mm))

    their_address = address.replace('\n', '<br />')
    their_address = Paragraph(their_address, style['Normal'])
    their_title = Paragraph('Name und Anschrift des Zuwendenden',
                            style['Heading5'])
    story.append(
        Table(
            [[their_title], [their_address]],
            colWidths=[doc.width * 1],
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 1), 0.5, colors.black),
            ]),
        ))
    story.append(Spacer(1, 5 * mm))

    data = [
        [_('Product'), _('Tax rate'),
         _('Net'), _('Gross')],
    ]
    data = [['Art', 'in Ziffern', 'in Buchstaben', 'Datum']]
    if fees:
        data.append([
            'Beiträge',
            CURRENCY.format(fees),
            lib_num2words(fees, lang='de'), year
        ])
    if donations:
        data.append([
            'Spenden',
            CURRENCY.format(donations),
            lib_num2words(donations, lang='de'), year
        ])
    last_row = len(data) - 1

    story.append(
        Table(
            data=data,
            colWidths=[
                doc.width * 0.15, doc.width * 0.15, doc.width * 0.5,
                doc.width * 0.2
            ],
            style=TableStyle([
                ('FONTSIZE', (0, 0), (3, last_row), FONTSIZE),
                ('ALIGN', (0, 0), (1, last_row), 'LEFT'),
                ('ALIGN', (3, 0), (3, last_row), 'RIGHT'),
                ('BOX', (0, 0), (3, last_row), 1.0, colors.black),
                ('GRID', (0, 0), (3, last_row), 0.5, colors.black),
            ]),
        ))
    story.append(Spacer(1, 5 * mm))

    story.append(
        Paragraph(
            'Es handelt sich NICHT um den Verzicht auf Erstattung von Aufwendungen.',
            style['Normal']))
    story.append(Spacer(1, 5 * mm))
    loong = 'Wir sind wegen Förderung {zwecke} nach dem Freistellungsbescheid bzw. nach der Anlage zum Körperschaftssteuerbescheid des Finanzamts {amt} StNr. {nummer} vom {datum} für den letzten Veranlagungszeitraum {zeitraum} nach § 5 Abs. 1 Nr. 9 des Körperschaftssteuergesetzes von der Körperschaftssteuer und nach § 3 Nr. 6 des Gewerbesteuergesetzes von der Gewerbesteuer befreit.'
    loong = loong.format(
        zwecke=local_settings.reason,
        amt=local_settings.finanzamt,
        nummer=local_settings.vat_id,
        datum=local_settings.notification_date,
        zeitraum=local_settings.veranlagungszeitraum,
    )
    story.append(Paragraph(loong, style['Normal']))
    story.append(Spacer(1, 5 * mm))
    story.append(
        Table(
            [[
                Paragraph(
                    'Es wird bestätigt, dass die Zuwendung nur zur Förderung {zwecke} verwendet wird.'
                    .format(zwecke=local_settings.reason), style['Normal'])
            ]],
            colWidths=[doc.width * 1],
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 0), 0.5, colors.black),
            ]),
        ))

    story.append(Spacer(1, 25 * mm))
    data = [[
        '{location}, {date}'.format(location=local_settings.location,
                                    date=now().date().isoformat())
    ], ['(Ort, Datum, und Unterschrift des Zuwendungsempfängers)']]
    story.append(
        Table(
            data=data,
            colWidths=[doc.width],
            style=TableStyle([
                ('LINEABOVE', (0, 1), (0, 1), 1.0, colors.black),
            ]),
        ))

    story.append(Spacer(1, 5 * mm))
    disclaimer1 = 'Wer vorsätzlich oder grob fahrlässig eine unrichtige Zuwendungsbestätigung erstellt oder wer veranlasst, dass Zuwendungen nicht zu den in der Zuwendungsbestätigung angegebenen steuerbegünstigten Zwecken verwendet werden, haftet für die Steuer, die dem Fiskus durch einen etwaigen Abzug der Zuwendungen beim Zuwendenden entgeht (§10b Abs. 4 EStG, §9 Abs. 3 KStG, §9 Nr. 5 GewStG).'
    disclaimer2 = 'Diese Bestätigung wird nicht als Nachweis für die steuerliche Berücksichtigung der Zuwendung anerkannt, wenn das Datum des Freistellungsbescheides länger als 5 Jahre bzw. das Datum der vorläufigen Bescheinigung länger als 3 Jahre seit Ausstellung der Bestätigung zurückliegt (BMF vom 15.12.1994 – BStBl I S. 884).'
    story.append(Paragraph('Hinweis', style['Heading5']))
    story.append(Paragraph(disclaimer1, style['Normal']))
    story.append(Paragraph(disclaimer2, style['Normal']))

    doc.build(story)
    _buffer.seek(0)
    doc = Document.objects.create(
        title='Zuwendungsbestätigung {}'.format(year),
        category=DOCUMENT_CATEGORY,
        member=member,
    )
    doc.document.save(
        'spenden/spenden_{}_{}_{}.pdf'.format(year, member.number,
                                              member.name),
        ContentFile(_buffer.read()))
    doc.save()
    return doc.document.url
Пример #2
0
def export_courses(data):
    try:
        for i in range(0, len(data)):
            tmp = int(data[i][0])
            LOGGER.debug(tmp)
            data[i][0] = convert_time(tmp)
            LOGGER.debug(convert_time(tmp))
        doc = SimpleDocTemplate('export.pdf',
                                rightMargin=0,
                                leftMargin=0,
                                topMargin=20,
                                bottomMargin=0,
                                pagesize=letter)

        elements = []
        im = Image("static/ban.png", 7 * inch, 0.8 * inch)
        elements.append(im)
        styleSheet = getSampleStyleSheet()
        elements.append(
            Paragraph(
                '''<para fontSize="18"><br/><br/>DATE DU RELEVE : ''' +
                str(datetime.now().strftime("%d-%m-%Y %H:%M")) +
                '''<br/><br/></para>''', styleSheet["Normal"]))
        head = ('DATE', 'LIEU', 'LABO', 'COURSIER', 'NB_TOTAL', 'SANGUINS',
                'AUTRES')
        heads = [head]
        h = Table(heads)
        table_style = TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ])
        h.setStyle(table_style)
        h.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.green)
                               ]))
        h._argW[0] = 1.3 * inch
        h._argW[1] = 1.5 * inch
        h._argW[2] = 0.7 * inch
        h._argW[3] = 1.5 * inch
        h._argW[4] = 0.9 * inch
        h._argW[5] = 0.9 * inch
        h._argW[6] = 0.9 * inch
        for i in range(0, len(h._argH)):
            h._argH[i] = 0.25 * inch
        elements.append(h)
        if not len(data) == 0:
            t = Table(data)
            t.setStyle(table_style)
            t._argW[0] = 1.3 * inch
            t._argW[1] = 1.5 * inch
            t._argW[2] = 0.7 * inch
            t._argW[3] = 1.5 * inch
            t._argW[4] = 0.9 * inch
            t._argW[5] = 0.9 * inch
            t._argW[6] = 0.9 * inch
            for i in range(0, len(t._argH)):
                t._argH[i] = 0.25 * inch
            table_style = []
            for i, row in enumerate(t._argH):
                if i % 2 == 0:
                    table_style.append(
                        ('BACKGROUND', (0, i), (-1, i), colors.lightgrey))
                else:
                    table_style.append(
                        ('BACKGROUND', (0, i), (-1, i), colors.white))
            t.setStyle(TableStyle(table_style))
            elements.append(t)
        doc.build(elements)
    except Exception as e:
        LOGGER.error("Error in export_courses(): " + str(e))
Пример #3
0
def motion_to_pdf(pdf, motion):
    """
    Create a PDF for one motion.
    """
    identifier = ''
    if motion.identifier:
        identifier = ' %s' % motion.identifier
    pdf.append(
        Paragraph('%s%s: %s' % (_('Motion'), identifier, escape(motion.title)),
                  stylesheet['Heading1']))

    motion_data = []

    # submitter
    cell1a = []
    cell1a.append(Spacer(0, 0.2 * cm))
    cell1a.append(
        Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("Submitter"),
                  stylesheet['Heading4']))
    cell1b = []
    cell1b.append(Spacer(0, 0.2 * cm))
    for submitter in motion.submitters.all():
        cell1b.append(Paragraph(str(submitter), stylesheet['Normal']))
    motion_data.append([cell1a, cell1b])

    # TODO: choose this in workflow
    if motion.state.allow_submitter_edit:
        # Cell for the signature
        cell2a = []
        cell2b = []
        cell2a.append(
            Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("Signature"),
                      stylesheet['Heading4']))
        cell2b.append(Paragraph(42 * "_", stylesheet['Signaturefield']))
        cell2b.append(Spacer(0, 0.1 * cm))
        cell2b.append(Spacer(0, 0.2 * cm))
        motion_data.append([cell2a, cell2b])

    # supporters
    if config['motions_min_supporters']:
        cell3a = []
        cell3b = []
        cell3a.append(
            Paragraph(
                "<font name='Ubuntu-Bold'>%s:</font><seqreset id='counter'>" %
                _("Supporters"), stylesheet['Heading4']))
        supporters = motion.supporters.all()
        for supporter in supporters:
            cell3b.append(
                Paragraph("<seq id='counter'/>.&nbsp; %s" % str(supporter),
                          stylesheet['Normal']))
        cell3b.append(Spacer(0, 0.2 * cm))
        motion_data.append([cell3a, cell3b])

    # Motion state
    cell4a = []
    cell4b = []
    cell4a.append(
        Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("State"),
                  stylesheet['Heading4']))
    cell4b.append(Paragraph(_(motion.state.name), stylesheet['Normal']))
    motion_data.append([cell4a, cell4b])

    # Version number
    if motion.versions.count() > 1:
        version = motion.get_active_version()
        cell5a = []
        cell5b = []
        cell5a.append(
            Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("Version"),
                      stylesheet['Heading4']))
        cell5b.append(
            Paragraph("%s" % version.version_number, stylesheet['Normal']))
        motion_data.append([cell5a, cell5b])

    # voting result
    polls = []
    for poll in motion.polls.all():
        if not poll.has_votes():
            continue
        polls.append(poll)

    if polls:
        cell6a = []
        cell6b = []
        cell6a.append(
            Paragraph("<font name='Ubuntu-Bold'>%s:</font>" % _("Vote result"),
                      stylesheet['Heading4']))
        ballotcounter = 0
        for poll in polls:
            ballotcounter += 1
            option = poll.get_options()[0]
            yes, no, abstain = (option['Yes'], option['No'], option['Abstain'])
            valid, invalid, votescast = ('', '', '')
            if poll.votesvalid is not None:
                valid = "<br/>%s: %s" % (_("Valid votes"),
                                         poll.print_votesvalid())
            if poll.votesinvalid is not None:
                invalid = "<br/>%s: %s" % (_("Invalid votes"),
                                           poll.print_votesinvalid())
            if poll.votescast is not None:
                votescast = "<br/>%s: %s" % (_("Votes cast"),
                                             poll.print_votescast())
            if len(polls) > 1:
                cell6b.append(
                    Paragraph("%s. %s" % (ballotcounter, _("Vote")),
                              stylesheet['Bold']))
            cell6b.append(
                Paragraph(
                    "%s: %s <br/> %s: %s <br/> %s: %s <br/> %s %s %s" %
                    (_("Yes"), yes, _("No"), no, _("Abstain"), abstain, valid,
                     invalid, votescast), stylesheet['Normal']))
            cell6b.append(Spacer(0, 0.2 * cm))
        motion_data.append([cell6a, cell6b])

    # Creating Table
    table = Table(motion_data)
    table._argW[0] = 4.5 * cm
    table._argW[1] = 11 * cm
    table.setStyle(
        TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'TOP')]))
    pdf.append(table)
    pdf.append(Spacer(0, 1 * cm))

    # motion title
    pdf.append(Paragraph(escape(motion.title), stylesheet['Heading3']))

    # motion text
    convert_html_to_reportlab(pdf, motion.text)
    pdf.append(Spacer(0, 1 * cm))

    # motion reason
    if motion.reason:
        pdf.append(Paragraph(_("Reason") + ":", stylesheet['Heading3']))
        convert_html_to_reportlab(pdf, motion.reason)
    return pdf
Пример #4
0
def generatePdf():
    import time
    from reportlab.lib.enums import TA_JUSTIFY
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch

    doc = SimpleDocTemplate("report/static/Relatorio.pdf",
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    Story = []
    logo = "report/static/currentGraphic.png"
    logo2 = "report/static/voltageGraphic.png"
    logo3 = "report/static/activePowerGraphic.png"
    logo4 = "report/static/reactivePowerGraphic.png"
    logo5 = "report/static/apparentPowerGraphic.png"

    magName = "Pythonista"
    issueNum = 12
    subPrice = "99.00"
    limitedDate = "03/05/2010"
    freeGift = "tin foil hat"

    formatted_time = time.ctime()
    full_name = "SME-UnB"
    address_parts = ["Campus Universitario UnB", "Brasilia-DF, 70910-900"]

    im = Image(logo, 8 * inch, 5 * inch)
    im2 = Image(logo2, 8 * inch, 5 * inch)
    im3 = Image(logo3, 8 * inch, 5 * inch)
    im4 = Image(logo4, 8 * inch, 5 * inch)
    im5 = Image(logo5, 8 * inch, 5 * inch)

    Story.append(im)
    Story.append(im2)
    Story.append(im3)
    Story.append(im4)
    Story.append(im5)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>%s</font>' % formatted_time

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))
    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Story.append(Paragraph(ptext, styles["Normal"]))

    Story.append(Spacer(1, 12))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>{ % trans Report Energy Monitoring % }</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))

    doc.build(Story)
Пример #5
0
 def _generate_documents_column(self, documents,
                                style: StyleSheet1) -> List[Flowable]:
     return [Paragraph(file_name, style) for file_name in documents]
Пример #6
0
def print_emp_report(request, fid):
    emp = NonPermanent.objects.select_related().get(parent_id=request.session['matched_employee_id'])
    reports = NonPermanentUnemploymentMonth.objects.select_related().filter(employee_id=request.session['matched_employee_id'],insurance_file=fid)
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=emp_report.pdf'
    registerFont(TTFont('DroidSans', os.path.join(settings.MEDIA_ROOT,
                                                  'DroidSans.ttf')))
    registerFont(TTFont('DroidSans-Bold', os.path.join(settings.MEDIA_ROOT,
                                                       'DroidSans-Bold.ttf')))

    doc = SimpleDocTemplate(response, pagesize=A4)
    doc.topMargin = 1.0 * cm
    doc.leftMargin = 1.5 * cm
    doc.rightMargin = 1.5 * cm

    elements = []
    head_logo = getSampleStyleSheet()
    head_logo.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                 fontName='DroidSans', fontSize=8))
    heading_style = getSampleStyleSheet()
    heading_style.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                     fontName='DroidSans-Bold',
                                     fontSize=12))
    heading_style.add(ParagraphStyle(name='Spacer', spaceBefore=5,
                                     spaceAfter=5,
                                     fontName='DroidSans-Bold',
                                     fontSize=12))
    signature = getSampleStyleSheet()
    signature.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                 fontName='DroidSans', fontSize=10))
    tbl_style = getSampleStyleSheet()

    tbl_style.add(ParagraphStyle(name='Left', alignment=TA_LEFT,
                                 fontName='DroidSans', fontSize=10))
    tbl_style.add(ParagraphStyle(name='Right', alignment=TA_RIGHT,
                                 fontName='DroidSans', fontSize=10))
    tbl_style.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                                 fontName='DroidSans', fontSize=10))

    tbl_style.add(ParagraphStyle(name='BoldLeft', alignment=TA_LEFT,
                                 fontName='DroidSans-Bold', fontSize=10))

    tsl = [('ALIGN', (0, 0), (-1, -1), 'CENTER'),
           ('FONT', (0, 0), (-1, 0), 'DroidSans'),
           ('FONTSIZE', (0, 0), (-1, 0), 8),
           ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
           ('TOPPADDING', (0, 0), (-1, -1), 0)]
    tsh = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
           ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]
    ts = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
          ('FONT', (0, 0), (-1, 0), 'DroidSans'),
          ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
          ('GRID', (0, 0), (-1, -1), 0.5, colors.black)]
    tsf = [('ALIGN', (1, 1), (-1, -1), 'CENTER')]

    for r in reports:
        data = []
        elements.append(Paragraph(u'ΒΕΒΑΙΩΣΗ ΕΡΓΟΔΟΤΗ', heading_style['Center']))
        elements.append(Paragraph(u' ', heading_style['Spacer']))

        data.append([Paragraph(u'ΕΠΩΝΥΜΙΑ ΕΡΓΟΔΟΤΗ ', tbl_style['Left']) , Paragraph(u'Διεύθυνση ΔΕ %s' % SETTINGS['dide_place'], tbl_style['Left'])])

        data.append([Paragraph(u'ΑΡΙΘΜΟΣ ΜΗΤΡΩΟΥ: %s' %  SETTINGS['ika_code_dde'], tbl_style['Left']), Paragraph(u'Α.Φ.Μ. ΕΡΓΟΔΟΤΗ: %s' % SETTINGS['afm_dide'], tbl_style['Left'])])

        data.append([Paragraph(u'ΑΡΜΟΔΙΟ ΥΠΟΚΑΤΑΣΤΗΜΑ ΙΚΑ ΕΛΕΓΧΟΥ ', tbl_style['Left']), Paragraph(u' ', tbl_style['Left'])])
        data.append([Paragraph(u'ΚΩΔΙΚΟΣ - ΟΝΟΜΑΣΙΑ ', tbl_style['Left']), Paragraph(u'%s' % SETTINGS['ika_code'] , tbl_style['Left'])])

        table = Table(data, style=tsf, colWidths=[7.0 * cm, 11.0 * cm])
        elements.append(table)
        elements.append(Paragraph(u' ', heading_style['Spacer']))

        data = []


        elements.append(Paragraph(u'Βεβαιώνουμε ότι:' , tbl_style['Left']))
        elements.append(Paragraph(u'Ο/Η ασφαλισμένος με τα κάτωθι ασφαλιστικά στοιχεία απασχολήθηκε στην υπηρεσία μας κατά τις μισθολογικές περιόδους που ακολουθούν:' , tbl_style['Left']))

        elements.append(Paragraph(u' ', heading_style['Spacer']))

        elements.append(Paragraph(u'ΣΤΟΙΧΕΙΑ ΥΠΑΛΛΗΛΟΥ', tbl_style['BoldLeft']))

        data.append([Paragraph(u'ΑΡ. ΠΑΡΑΡΤ. / Κ.Α.Δ. ', tbl_style['Left']), Paragraph(u'%s' % SETTINGS['subject_kad'], tbl_style['Right'])])
        data.append([Paragraph(u'ΑΜΑ: ', tbl_style['Left']), Paragraph(u'%s' % emp.ama, tbl_style['Right'])])
        data.append([Paragraph(u'Α.Μ.Κ.Α.: ', tbl_style['Left']), Paragraph(u'%s' % emp.social_security_registration_number, tbl_style['Right'])])

        data.append([Paragraph(u'ΕΠΩΝΥΜΟ: ', tbl_style['Left']), Paragraph(u'%s' % emp.lastname, tbl_style['Right'])])
        data.append([Paragraph(u'ΟΝΟΜΑ: ', tbl_style['Left']), Paragraph(u'%s' % emp.firstname, tbl_style['Right'])])
        data.append([Paragraph(u'ΟΝΟΜΑ ΠΑΤΡΟΣ: ', tbl_style['Left']), Paragraph(u'%s' % emp.fathername, tbl_style['Right'])])
        data.append([Paragraph(u'ΟΝΟΜΑ ΜΗΤΡΟΣ: ', tbl_style['Left']), Paragraph(u'%s' % emp.mothername, tbl_style['Right'])])

        if emp.birth_date == None:
            data.append([Paragraph(u'ΗΜΕΡΟΜΗΝΙΑ ΓΕΝΝΗΣΕΩΣ: ', tbl_style['Left']), Paragraph(u' ', tbl_style['Right'])])

        else:
            data.append([Paragraph(u'ΗΜΕΡΟΜΗΝΙΑ ΓΕΝΝΗΣΕΩΣ: ', tbl_style['Left']), Paragraph(u'%s / %s / %s' % (emp.birth_date.day, emp.birth_date.month, emp.birth_date.year), tbl_style['Right'])])

        data.append([Paragraph(u'Α.Φ.Μ.: ', tbl_style['Left']), Paragraph(u'%s' % emp.vat_number, tbl_style['Right'])])
        data.append([Paragraph(u'ΚΩΔΙΚΟΣ ΕΙΔΙΚΟΤΗΤΑΣ: ', tbl_style['Left']), Paragraph(u'%s' % emp.type(), tbl_style['Right'])])
        if emp.other_social_security:
            ec = emp.other_social_security.code
        else:
            ec = '101'

        data.append([Paragraph(u'ΠΑΚΕΤΟ ΚΑΛΥΨΗΣ: ', tbl_style['Left']), Paragraph(u'%s' % ec, tbl_style['Right'])])
        data.append([Paragraph(u'ΜΙΣΘΟΛΟΓΙΚΗ ΠΕΡΙΟΔΟΣ: ', tbl_style['Left']), Paragraph(u'%s / %s' % (r.month, r.year), tbl_style['Right'])])
        if r.insured_from.strip() in ('', '/  /'):
            dtf = '01/'+ str(r.month) + '/' + str(r.year)
            dtt = str(calendar.monthrange(r.year, r.month)[1]) + '/' + str(r.month) + '/' + str(r.year)
        else:
            dtf = r.insured_from
            dtt = r.insured_to

        data.append([Paragraph(u'ΑΠΟ ΗΜΕΡΟΜΗΝΙΑ ΑΠΑΣΧΟΛΗΣΗΣ: ', tbl_style['Left']), Paragraph(u'%s' % dtf, tbl_style['Right'])])
        data.append([Paragraph(u'ΕΩΣ ΗΜΕΡΟΜΗΝΙΑ ΑΠΑΣΧΟΛΗΣΗΣ: ', tbl_style['Left']), Paragraph(u'%s' % dtt, tbl_style['Right'])])
        data.append([Paragraph(u'ΤΥΠΟΣ ΑΠΟΔΟΧΩΝ: ', tbl_style['Left']), Paragraph(u'%s' % r.pay_type, tbl_style['Right'])])
        data.append([Paragraph(u'ΗΜΕΡΕΣ ΑΣΦΑΛΙΣΗΣ: ', tbl_style['Left']), Paragraph(u'%s' % r.days_insured, tbl_style['Right'])])
        lpam = r.total_earned.split('.')[0]
        rpam = r.total_earned.split('.')[1]
        if len(rpam) == 1:
            rpam = rpam + '0'
        data.append([Paragraph(u'ΑΠΟΔΟΧΕΣ: ', tbl_style['Left']), Paragraph(u'%s.%s' % (lpam, rpam), tbl_style['Right'])])

        lpam = r.employee_contributions.split('.')[0]
        rpam = r.employee_contributions.split('.')[1]
        if len(rpam) == 1:
            rpam = rpam + '0'
        data.append([Paragraph(u'ΕΙΣΦΟΡΕΣ ΑΣΦΑΛΙΣΜΕΝΟΥ: ', tbl_style['Left']), Paragraph(u'%s.%s' % (lpam, rpam), tbl_style['Right'])])

        lpam = r.employer_contributions.split('.')[0]
        rpam = r.employer_contributions.split('.')[1]
        if len(rpam) == 1:
            rpam = rpam + '0'
        data.append([Paragraph(u'ΕΙΣΦΟΡΕΣ ΕΡΓΟΔΟΤΗ: ', tbl_style['Left']), Paragraph(u'%s.%s' % (lpam, rpam), tbl_style['Right'])])

        lpam = r.total_contributions.split('.')[0]
        rpam = r.total_contributions.split('.')[1]
        if len(rpam) == 1:
            rpam = rpam + '0'

        data.append([Paragraph(u'ΣΥΝΟΛΙΚΕΣ ΕΙΣΦΟΡΕΣ: ', tbl_style['Left']), Paragraph(u'%s.%s' % (lpam, rpam), tbl_style['Right'])])
        data.append([Paragraph(u'ΚΑΤΑΒΛ. ΕΙΣΦΟΡΕΣ: ', tbl_style['Left']), Paragraph(u'%s.%s' % (lpam, rpam), tbl_style['Right'])])


        table = Table(data, style=tsf, colWidths=[10.0 * cm, 8.0 * cm])
        elements.append(table)

        data = []

        elements.append(Paragraph(u'Η παραπάνω βεβαίωση χορηγείται για απόδειξη της ασφάλισης στις προαναφερθείσες περιόδους.', tbl_style['Left']))
        elements.append(Paragraph(u'ΠΑΡΑΤΗΡΗΣΗ', tbl_style['Left']))

        elements.append(Paragraph(u'Τα αναγραφόμενα στην παρούσα Βεβαίωση ασφαλιστικά στοιχεία λαμβάνονται υπόψη μέχρι την επεξεργασία της Α.Π.Δ. των συγκεκριμένων μισθολογικών περιόδων και την υποβολή και έκδοση από το ΙΚΑ του αντίστοιχου Αποσπάσματος Ατομικού Λογαριασμού Ασφάλισης.', tbl_style['Justify']))

        today = datetime.date.today()

        data.append([Paragraph(u' ', signature['Center']) ,Paragraph(u'Ρόδος, %s / %s / %s' %
                               (today.day, today.month, today.year), signature['Center'])])

        table = Table(data, style=tsf, colWidths=[9.0 * cm, 8.0 * cm])
        elements.append(table)
        elements.append(Paragraph(u' ', heading_style['Spacer']))

        data = []

        sign = os.path.join(settings.MEDIA_ROOT, "signature.png")
        im = Image(sign)
        im.drawHeight = 3.2 * cm
        im.drawWidth = 6.5 * cm

        data.append([Paragraph(u' ', signature['Center']), im])

        table = Table(data, style=tsf, colWidths=[10.0 * cm, 7.0 * cm])
        elements.append(table)
        elements.append(PageBreak())

    doc.build(elements)
    return response
Пример #7
0
def export_pdf_log(request,
                   pk,
                   images=False,
                   comments=False,
                   uidb64=None,
                   token=None):
    '''
    Show the workout schedule
    '''
    user = request.user

    comments = bool(int(comments))
    images = bool(int(images))

    # Load the workout
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            schedule = get_object_or_404(Schedule, pk=pk)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        schedule = get_object_or_404(Schedule, pk=pk, user=user)

    # Create the HttpResponse object with the appropriate PDF headers.
    # and use it to the create the PDF using it as a file like object
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            leftMargin=cm,
                            rightMargin=cm,
                            topMargin=0.5 * cm,
                            bottomMargin=0.5 * cm,
                            title=_('Workout'),
                            author='wger Workout Manager',
                            subject='Schedule for {0}'.format(
                                request.user.username))

    # container for the 'Flowable' objects
    elements = []

    # Set the title
    p = Paragraph(u'<para align="center">{0}</para>'.format(schedule),
                  styleSheet["HeaderBold"])
    elements.append(p)
    elements.append(Spacer(10 * cm, 0.5 * cm))

    # Iterate through the Workout and render the training days
    for step in schedule.schedulestep_set.all():
        p = Paragraph(
            u'<para>{0} {1}</para>'.format(step.duration, _('Weeks')),
            styleSheet["HeaderBold"])
        elements.append(p)
        elements.append(Spacer(10 * cm, 0.5 * cm))

        for day in step.workout.canonical_representation['day_list']:
            elements.append(
                render_workout_day(day,
                                   images=images,
                                   comments=comments,
                                   nr_of_weeks=7))
            elements.append(Spacer(10 * cm, 0.5 * cm))

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    url = reverse('manager:schedule:view', kwargs={'pk': schedule.id})
    elements.append(render_footer(request.build_absolute_uri(url)))

    # write the document and send the response to the browser
    doc.build(elements)
    response[
        'Content-Disposition'] = 'attachment; filename=Schedule-{0}-log.pdf'.format(
            pk)
    response['Content-Length'] = len(response.content)
    return response
Пример #8
0
class PostingReportPDFRenderer:
    label_style = ParagraphStyle(name="label",
                                 fontName="Helvetica",
                                 fontSize=8,
                                 leading=5 * mm)
    table_header_style = ParagraphStyle(name="th",
                                        fontName="Courier-Bold",
                                        fontSize=8,
                                        alignment=TA_CENTER)
    signature_style = ParagraphStyle(name="sign",
                                     fontName="Helvetica",
                                     fontSize=8,
                                     leading=10,
                                     alignment=TA_CENTER)

    heading_title = "Lista de Postagem".upper()
    header_label_col1 = ("<b>N° da Lista:</b> {!s}<br/>"
                         "<b>Contrato:</b> {!s}<br/>"
                         "<b>Cód. Administrativo:</b> {!s}<br/>"
                         "<b>Cartão:</b> {!s}")
    header_label_col2 = ("<b>Remetente:</b> {!s}<br/>"
                         "<b>Cliente:</b> {!s}<br/>"
                         "<b>Endereço:</b> {!s}<br/>"
                         "{!s}")
    header_label_col3 = "<b>Telefone:</b> {!s}<br/>"

    table_style = [
        ('FONTNAME', (0, 0), (-1, -1), "Courier"),
        ('FONTNAME', (0, 0), (-1, 0), "Courier-Bold"),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('ALIGN', (6, 1), (6, -1), "RIGHT"),
    ]
    col_widths = (25 * mm, 15 * mm, 10 * mm, 6 * mm, 6 * mm, 6 * mm, 20 * mm,
                  15 * mm, 13 * mm, 84 * mm)
    max_receiver_name_size = 48  # chars
    table_header = ("Nº do Objeto", "CEP", "Peso", "AR", "MP", "VD",
                    Paragraph("Valor<br/>Declarado", style=table_header_style),
                    Paragraph("Nota<br/>Fiscal", style=table_header_style),
                    "Volume", "Destinatário")
    table_max_rows = 29
    yes, no = "S", "N"

    footer_title_text = "Apresentar esta lista em caso de pedido de informações".upper(
    )
    footer_disclaimer = "Estou ciente do disposto na clásula terceria do contrato de prestação de serviços"
    footer_stamp_text = "Carimbo e assinatura / Matrícula dos Correios"
    footer_signature_text = (
        "_________________________________________________________<br/>"
        "ASSINATURA REMETENTE<br/><br/><br/>"
        "Obs: 1o via p/ a Unidade de Postagem e 2o via p/ o cliente")

    def __init__(self,
                 page_size=pagesizes.A4,
                 shipping_labels_margin=(0, 0),
                 posting_list_margin=(5 * mm, 5 * mm)):
        self.shipping_labels = []  # type: List[ShippingLabel]
        self._tracking_codes = set()

        self.page_size = page_size
        self.page_width = page_size[0]
        self.page_height = page_size[1]

        self.posting_list = None  # type: PostingList
        self.posting_list_margin = posting_list_margin

        self.shipping_labels_margin = shipping_labels_margin
        self.shipping_labels_width = self.page_width - (
            2 * shipping_labels_margin[0])
        self.shipping_labels_height = self.page_height - (
            2 * shipping_labels_margin[1])

        self.col_size = self.shipping_labels_width / 2
        self.row_size = self.shipping_labels_height / 2
        self._label_position = (
            (shipping_labels_margin[0], self.page_height / 2),
            (shipping_labels_margin[0] + self.col_size, self.page_height / 2),
            (shipping_labels_margin[0], shipping_labels_margin[1]),
            (shipping_labels_margin[0] + self.col_size,
             shipping_labels_margin[1]),
        )

    def set_posting_list(self, posting_list: PostingList):
        if not posting_list.closed:
            raise RendererError("Cannot render an open posting list")

        self.posting_list = posting_list
        for shipping_label in posting_list.shipping_labels.values():
            self.add_shipping_label(shipping_label)

    def add_shipping_label(self, shipping_label: ShippingLabel):
        if shipping_label in self.shipping_labels:
            raise RendererError("Shipping Label {!s} already added".format(
                shipping_label.tracking_code))
        self.shipping_labels.append(shipping_label)

    def draw_grid(self, canvas):
        canvas.setLineWidth(0.2)
        canvas.setStrokeColor(colors.gray)
        canvas.line(
            self.shipping_labels_margin[0], self.page_height / 2,
            self.shipping_labels_width + self.shipping_labels_margin[0],
            self.page_height / 2)
        canvas.line(
            self.page_width / 2, self.shipping_labels_margin[1],
            self.page_width / 2,
            self.shipping_labels_height + self.shipping_labels_margin[1])

    # noinspection PyUnusedLocal
    def _posting_list_header(self, pdf, width, x1, y1, x2, y2):
        canvas = pdf.canvas

        # logo
        logo = ImageReader(self.posting_list.logo)
        canvas.drawImage(logo,
                         x1,
                         y2 - 10.3 * mm,
                         height=8 * mm,
                         preserveAspectRatio=True,
                         anchor="sw",
                         mask="auto")
        # head1
        canvas.setFont("Helvetica-Bold", size=14)
        canvas.drawCentredString(
            x2 - ((width - 40 * mm) / 2), y2 - 9 * mm,
            "Empresa Brasileira de Correios e Telégrafos".upper())
        # box
        canvas.setLineWidth(0.5)
        canvas.rect(x1, y2 - 45 * mm, width, 30 * mm)
        canvas.drawCentredString(x1 + width / 2, y2 - (15 * mm) - 15,
                                 self.heading_title)
        # header info
        spacer = 5 * mm
        col_width = width / 4
        col = 0
        header = self.header_label_col1.format(
            self.posting_list.number, self.posting_list.contract,
            self.posting_list.posting_card.administrative_code,
            self.posting_list.posting_card)
        text = Paragraph(header, style=self.label_style)
        text.wrap(col_width, 30 * mm)
        text.drawOn(canvas, x1 + spacer + col * col_width, y2 - (43 * mm))
        col = 1
        header = self.header_label_col2.format(
            self.posting_list.sender.name[:30],
            self.posting_list.contract.customer_name[:30],
            self.posting_list.sender.display_address[0][:30],
            self.posting_list.sender.display_address[1][:30])
        text = Paragraph(header, style=self.label_style)
        text.wrap(col_width * 2, 30 * mm)
        text.drawOn(canvas, x1 + spacer + col * col_width, y2 - (43 * mm))
        col = 3
        header = self.header_label_col3.format(
            self.posting_list.sender.phone.display())
        text = Paragraph(header, style=self.label_style)
        text.wrap(col_width, 30 * mm)
        text.drawOn(canvas, x1 + spacer + col * col_width, y2 - (43 * mm))
        code = createBarcodeDrawing("Code128",
                                    value=str(self.posting_list.number),
                                    width=col_width * 0.6,
                                    height=10 * mm,
                                    quiet=0)
        code.drawOn(canvas, x1 + spacer + col * col_width, y2 - (35 * mm))

    # noinspection PyUnusedLocal
    def _posting_list_footer(self, pdf, width, x1, y1, x2, y2):
        canvas = pdf.canvas

        canvas.rect(x1, y1, width, 38 * mm)
        canvas.setFont("Helvetica-Bold", size=9)
        canvas.drawCentredString(x2 - (width / 2), y1 + 38 * mm - 10,
                                 self.footer_title_text)
        canvas.setFont("Helvetica", size=8)
        canvas.drawString(x1 + 2 * mm, y1 + 28 * mm, self.footer_disclaimer)
        text_width = stringWidth(self.footer_stamp_text, "Helvetica", 8)
        canvas.drawString(x2 - 2 * mm - text_width, y1 + 28 * mm,
                          self.footer_stamp_text)
        text = Paragraph(self.footer_signature_text,
                         style=self.signature_style)
        text.wrap(stringWidth(self.footer_disclaimer, "Helvetica", 8), 10 * mm)
        text.drawOn(canvas, x1 + 2 * mm, y1 + 2 * mm)

    # noinspection PyUnusedLocal
    def _posting_list_table(self, canvas, x1, y1, x2, y2, shipping_labels):
        style = self.table_style[:]
        table = [self.table_header]
        for i, shipping_label in enumerate(shipping_labels, start=1):
            row = (
                str(shipping_label.tracking_code),
                str(shipping_label.receiver.zip_code),
                str(shipping_label.package.posting_weight),
                self.yes if ExtraService.get(EXTRA_SERVICE_AR)
                in shipping_label else self.no,
                self.yes if ExtraService.get(EXTRA_SERVICE_MP)
                in shipping_label else self.no,
                self.yes if ExtraService.get(EXTRA_SERVICE_VD)
                in shipping_label else self.no,
                str(shipping_label.value).replace(".", ",")
                if shipping_label.value is not None else "",
                str(shipping_label.invoice_number),
                shipping_label.get_package_sequence(),
                shipping_label.receiver.name[:self.max_receiver_name_size],
            )

            # noinspection PyTypeChecker
            table.append(row)

            if i % 2:
                style.append(('BACKGROUND', (0, i), (-1, i), colors.lightgrey))

        table_flow = Table(
            table,
            colWidths=self.col_widths,
            style=TableStyle(style),
        )
        w, h = table_flow.wrap(0, 0)
        table_flow.drawOn(canvas, x1, y2 - h - 50 * mm)

    def render_posting_list(self, pdf=None) -> PDF:
        if pdf is None:
            pdf = PDF(self.page_size)
        canvas = pdf.canvas

        width = self.page_width - (2 * self.posting_list_margin[0])
        height = self.page_height - (2 * self.posting_list_margin[1])
        x1, y1 = self.posting_list_margin[0], self.posting_list_margin[1]
        x2, y2 = width + self.posting_list_margin[
            0], height + self.posting_list_margin[1]

        for start_group_pos in range(0, len(self.shipping_labels),
                                     self.table_max_rows):
            self._posting_list_header(pdf, width, x1, y1, x2, y2)

            group = self.shipping_labels[start_group_pos:start_group_pos +
                                         self.table_max_rows]
            self._posting_list_table(canvas, x1, y1, x2, y2, group)

            self._posting_list_footer(pdf, width, x1, y1, x2, y2)
            canvas.showPage()

        return pdf

    def render_labels(self, pdf=None) -> PDF:
        if pdf is None:
            pdf = PDF(self.page_size)

        canvas = pdf.canvas

        position = len(self._label_position) - 1
        for i, shipping_label in enumerate(self.shipping_labels):
            position = i % len(self._label_position)
            self.render_label(shipping_label, position, pdf)
            if position == len(self._label_position) - 1:
                self.draw_grid(canvas)
                canvas.showPage()

        if position != len(self._label_position) - 1:
            self.draw_grid(canvas)
            canvas.showPage()

        return pdf

    def render_label(self,
                     shipping_label: ShippingLabel,
                     position=0,
                     pdf=None) -> PDF:
        single_label = pdf is None
        if single_label:
            pdf = PDF(self.page_size)

        canvas = pdf.canvas
        label = ShippingLabelFlowable(shipping_label, self.col_size,
                                      self.row_size)
        label.drawOn(pdf.canvas, *self._label_position[position])

        if single_label:
            self.draw_grid(canvas)
            canvas.showPage()

        return pdf

    def render(self) -> PDF:
        pdf = PDF(self.page_size)
        self.render_posting_list(pdf)
        self.render_labels(pdf)
        return pdf
Пример #9
0
    def draw(self):
        canvas = self.canv
        canvas.setLineWidth(0.1)

        # logo
        logo = ImageReader(self.shipping_label.logo)
        canvas.drawImage(logo,
                         self.x1 + 5 * mm,
                         self.y2 - (27 * mm),
                         width=25 * mm,
                         preserveAspectRatio=True,
                         anchor="sw",
                         mask="auto")

        # datagrid
        datagrid = createBarcodeDrawing(
            "ECC200DataMatrix",
            value=self.shipping_label.get_datamatrix_info(),
            width=25 * mm,
            height=25 * mm)
        datagrid.drawOn(canvas, self.x1 + 40 * mm, self.y2 - (27 * mm))

        # symbol
        symbol = ImageReader(self.shipping_label.symbol)
        canvas.drawImage(symbol,
                         self.x1 + 70 * mm,
                         self.y2 - (27 * mm),
                         width=25 * mm,
                         preserveAspectRatio=True,
                         anchor="sw",
                         mask="auto")

        # header shipping_labels
        text = Paragraph("{}<br/>{}".format(self.shipping_label.get_invoice(),
                                            self.shipping_label.get_order()),
                         style=self.label_style)
        text.wrap(25 * mm, 14)
        text.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (28 * mm) - 14)

        text = Paragraph("{}<br/>{}".format(
            self.shipping_label.get_contract_number(),
            self.shipping_label.get_service_name()),
                         style=self.label_style)
        text.wrap(25 * mm, 14)
        text.drawOn(canvas, self.x1 + 40 * mm, self.y2 - (28 * mm) - 14)

        text = Paragraph("{}<br/>{}".format(
            self.shipping_label.get_package_sequence(),
            self.shipping_label.get_weight()),
                         style=self.label_style)
        text.wrap(25 * mm, 14)
        text.drawOn(canvas, self.x1 + 70 * mm, self.y2 - (28 * mm) - 14)

        # tracking
        canvas.setFont("Helvetica-Bold", 10)
        canvas.drawCentredString(self.x1 + 42.5 * mm, self.y2 - 40 * mm,
                                 self.shipping_label.get_tracking_code())
        code = createBarcodeDrawing("Code128",
                                    value=str(
                                        self.shipping_label.tracking_code),
                                    width=75 * mm,
                                    height=18 * mm,
                                    quiet=0)
        code.drawOn(canvas, 10 * mm, self.y2 - (59 * mm))

        # extra services (first three)
        first_row = self.y2 - (40 * mm) - 10  # font-size=10pt
        for extra_service in self.shipping_label.extra_services:
            if not extra_service.display_on_label:
                continue

            canvas.drawString(self.x2 - (10 * mm), first_row,
                              extra_service.code)
            first_row -= 14

        # receipt
        receipt_style = ParagraphStyle(name="label",
                                       fontName="Helvetica",
                                       fontSize=8,
                                       leading=14)
        text = Paragraph(self.shipping_label.receipt_template,
                         style=receipt_style)
        text.wrap(self.width - (10 * mm), 28)
        text.drawOn(canvas, self.x1 + (5 * mm), self.y2 - (60 * mm) - 28)

        # sender header
        canvas.setFillColor(colors.black)
        canvas.line(self.x1, self.y2 - (70 * mm), self.x2, self.y2 - (70 * mm))
        width = stringWidth(self.shipping_label.sender_header, "Helvetica",
                            10) + 2
        canvas.rect(self.x1, self.y2 - (70 * mm) - 14, width, 14, fill=True)

        canvas.setFont("Helvetica", 9)
        canvas.setFillColor(colors.white)
        canvas.drawString(self.x1 + 4, self.y2 - (70 * mm) - 10,
                          self.shipping_label.sender_header)

        carrier_logo = ImageReader(self.shipping_label.carrier_logo)
        canvas.drawImage(carrier_logo,
                         self.x2 - 20 * mm,
                         self.y2 - (70 * mm) - 12,
                         height=10,
                         preserveAspectRatio=True,
                         anchor="sw",
                         mask="auto")

        # receiver
        receiver_style = ParagraphStyle("receiver",
                                        fontName="Helvetica",
                                        fontSize=10,
                                        leading=15)
        text = Paragraph(self.shipping_label.get_receiver_data(),
                         style=receiver_style)
        text.wrap(self.width - 5 * mm, 24 * mm)
        text.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (98 * mm))

        # receiver zip barcode
        code = createBarcodeDrawing("Code128",
                                    value=str(
                                        self.shipping_label.receiver.zip_code),
                                    width=30 * mm,
                                    height=18 * mm,
                                    quiet=0)
        code.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (117 * mm))

        # text
        text_style = ParagraphStyle("text", fontName="Helvetica", fontSize=10)
        text = Paragraph(self.shipping_label.text, style=text_style)
        width = self.x2 - (self.x1 + (45 * mm))
        text.wrap(width, 15 * mm)
        text.breakLines(width)
        text.drawOn(canvas, self.x1 + (45 * mm), self.y2 - (98 * mm))

        # sender
        canvas.line(self.x1, self.y2 - (118 * mm), self.x2,
                    self.y2 - (118 * mm))
        sender_style = ParagraphStyle("sender",
                                      fontName="Helvetica",
                                      fontSize=9)
        text = Paragraph(self.shipping_label.get_sender_data(),
                         style=sender_style)
        text.wrap(self.width - 5 * mm, 22 * mm)
        text.drawOn(canvas, self.x1 + 5 * mm, self.y1 + 2 * mm)

        # border
        canvas.rect(self.x1, self.y1, self.width, self.height)
Пример #10
0
 def append_text(self, text, style, space):
     self.story_arr.append(Paragraph(text, style))
     self.story_arr.append(Spacer(1, space))
Пример #11
0
	def print_users(self, pk):
		
		reportlab_directory = os.path.dirname(reportlab.__file__)
		font_folder = os.path.join(reportlab_directory, "fonts")

		custom_font_folder = os.path.join(font_folder, "Arial.ttf")
		custom_font_bold_folder = os.path.join(font_folder, "Arial-bold.ttf")
		custom_font_italic_folder = os.path.join(font_folder, "Arial-italic.ttf")

		custom_font = TTFont("arial", custom_font_folder)
		custom_font_bold = TTFont("arial-bold", custom_font_bold_folder)
		custom_font_italic = TTFont("arial-italic", custom_font_italic_folder)

		pdfmetrics.registerFont(custom_font)
		pdfmetrics.registerFont(custom_font_bold)
		pdfmetrics.registerFont(custom_font_italic)

		registerFontFamily('hepsi', normal = "arial", bold = "arial-bold", italic = "arial-italic")

		
		
			
		
		buffer = self.buffer
		doc = SimpleDocTemplate(buffer,
			rightMargin=20,
			leftMargin=20,
			topMargin=20,
			bottomMargin=20,
			pagesize=self.pagesize)
		
		
		# Our container for 'Flowable' objects
		elements = []

		# A large collection of style sheets pre-made for us
		styles = getSampleStyleSheet()
		styles.add(ParagraphStyle(name='baslik', fontName = "arial", fontSize = 18, leading = 25, textColor = colors.red))
		styles.add(ParagraphStyle(name='alt-baslik', fontName = "arial", fontSize = 16, leading = 25, textColor = colors.red))
		styles.add(ParagraphStyle(name='paragraf', fontName = "arial", fontSize = 14, leading = 15))
		styles.add(ParagraphStyle(name='paragraf-bold', fontName = "arial", fontSize = 14, leading = 15))
		styles.add(ParagraphStyle(name='deneme', fontName = "hepsi", fontSize = 14, leading = 15))

		# Draw things on the PDF. Here's where the PDF generation happens.
		# See the ReportLab documentation for the full list of functionality.
		liste = [] 

		baslik = get_object_or_404(Baslik, pk = pk)
		dersler = baslik.ders_set.all()
		elements.append(Paragraph(baslik.title, styles["baslik"]))
		elements.append(Paragraph(baslik.content + "<br></br><br></br>", styles['paragraf']))
		for ders in dersler:
			elements.append(Paragraph(ders.title, styles['alt-baslik']))
			soup = BeautifulSoup(ders.content)				
			#paragraflar = soup.find_all("p")
			element_listesi = soup.find_all(["p", "table"])
			
			for element in element_listesi:
				if element.name =="p":
					paragraf = str(element) + "<br></br>" +  "<br></br>"
					elements.append(Paragraph(paragraf, styles['paragraf']))
				
				if element.name =="table":
					liste = []
					tr = element.findAll("tr")
					print("")
					#print(tr)
					print("")
					for i in tr:
						data = i.findAll(["th", "td"])
						data = [i.text for i in data]
						print("")
						#print(data)
						print("")
						print()
						
						print("")
						
						liste.append(data)
						#print(liste)
						print("")
						
					tstyle = TableStyle([("GRID", (0, 0), (-1, -1), 0.2, colors.red),
											  ('ALIGN',(0,0),(-1,-1),'LEFT'),
											  ("FONT", (0, 0), (-1, -1), "arial", 12),
											  ('VALIGN', (0,0),(-1,-1), "TOP"),
											  #('SPAN',(-0,-0),(-1,-1)),
											  #("BOX", (0, 0), (-1, -1), 0.2, colors.red),
							])
					print("LİSteeeeeeeeeeeeeee")
					print(liste,)
					t = Table(liste, rowHeights=50, colWidths=50)
					t.setStyle(tstyle)
					#t._argW[3]=5*inch
					elements.append(t)
				#elements.append(Paragraph("!!!Tablomuz burada!!!", styles['paragraf']))
					

		doc.build(elements)

		# Get the value of the BytesIO buffer and write it to the response.
		pdf = buffer.getvalue()
		buffer.close()
		return pdf
Пример #12
0
def receive_journal(request):
    """Печать истории принятия материала за день"""
    lab = Podrazdeleniya.objects.get(pk=request.GET.get(
        "lab_pk", request.user.doctorprofile.podrazdeleniye.pk))
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.platypus import Table, TableStyle
    from reportlab.lib import colors
    from reportlab.platypus import Paragraph
    from reportlab.lib.styles import getSampleStyleSheet

    styleSheet = getSampleStyleSheet()
    import os.path
    import collections
    import copy

    start = str(request.GET.get("start", "1"))
    group = str(request.GET.get("group", "-2"))
    return_type = str(request.GET.get("return", "pdf"))
    otd = str(request.GET.get("otd", "[]"))

    start = 1 if not start.isdigit() else int(start)
    group = -2 if group not in ["-2", "-1"] and (
        not group.isdigit() or not directory.ResearchGroup.objects.filter(
            pk=int(group)).exists()) else int(group)
    otd = [int(x) for x in json.loads(otd)]

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER,
                                        'OpenSans.ttf')))  # Загрузка шрифта

    response = HttpResponse(
        content_type='application/pdf')  # Формирование ответа
    response[
        'Content-Disposition'] = 'inline; filename="zhurnal_priema_materiala.pdf"'  # Content-Disposition inline для показа PDF в браузере
    from io import BytesIO
    buffer = BytesIO()  # Буфер
    from reportlab.pdfgen import canvas

    c = canvas.Canvas(buffer, pagesize=A4)  # Холст

    if return_type == "directions":
        tubes = TubesRegistration.objects.filter(
            issledovaniya__research__podrazdeleniye=lab,
            time_recive__gte=datetime.now().date(),
            doc_get__podrazdeleniye__pk__in=otd,
            doc_recive__isnull=False).order_by('time_recive', 'daynum')
    else:
        tubes = TubesRegistration.objects.filter(
            issledovaniya__research__podrazdeleniye=lab,
            time_recive__gte=datetime.now().date(),
            doc_get__podrazdeleniye__pk__in=otd,
            doc_recive__isnull=False).order_by(
                'issledovaniya__napravleniye__client__pk')

    labs = {}  # Словарь с пробирками, сгруппироваными по лаборатории
    directions = []
    vids = set()

    perpage = 47

    n_dict = {}

    n = 1
    for v in tubes:  # Перебор пробирок
        idv = v.id
        if idv in vids: continue
        vids.add(idv)
        iss = Issledovaniya.objects.filter(
            tubes__id=v.id)  # Получение исследований для пробирки

        if group == -1:
            iss = iss.filter(research__groups__isnull=True)
        elif group >= 0:
            iss = iss.filter(research__groups__pk=group)

        iss_list = collections.OrderedDict()  # Список исследований
        if v.doc_get:
            k = str(v.doc_get.podrazdeleniye.pk) + "@" + str(
                v.doc_get.podrazdeleniye)
        else:
            k = str(
                iss.first().napravleniye.doc.podrazdeleniye.pk) + "@" + str(
                    iss.first().napravleniye.doc.podrazdeleniye)
        if k not in n_dict.keys():
            n_dict[k] = 0
        for val in iss.order_by(
                "research__sort_weight"
        ):  # Цикл перевода полученных исследований в список
            iss_list[val.research.sort_weight] = val.research.title

        if len(iss_list) == 0:
            continue
        '''
        if n < start:
            n += 1
            continue'''
        if return_type == "pdf":
            n_dict[k] += 1
            if n_dict[k] >= start:
                if k not in labs.keys(
                ):  # Добавление списка в словарь если по ключу k нету ничего в словаре labs
                    labs[k] = []

                if perpage - len(labs[k]) % perpage < len(iss_list):
                    pre = copy.deepcopy(labs[k][len(labs[k]) - 1])
                    pre["researches"] = ""
                    for x in range(0, perpage - len(labs[k]) % perpage):
                        labs[k].append(pre)
                for value in iss_list:  # Перебор списка исследований
                    labs[k].append(
                        {
                            "type":
                            v.type.tube.title,
                            "researches":
                            iss_list[value],
                            "client-type":
                            iss[0].napravleniye.client.base.short_title,
                            "lab_title":
                            iss[0].research.get_podrazdeleniye().title,
                            "time":
                            strtime(v.time_recive),
                            "dir_id":
                            iss[0].napravleniye.pk,
                            "podr":
                            iss[0].napravleniye.doc.podrazdeleniye.title,
                            "receive_n":
                            str(n),
                            "tube_id":
                            str(v.id),
                            "direction":
                            str(iss[0].napravleniye.pk),
                            "history_num":
                            iss[0].napravleniye.history_num,
                            "n":
                            n_dict[k],
                            "fio":
                            iss[0].napravleniye.client.individual.fio(
                                short=True, dots=True)
                        }
                    )  # Добавление в список исследований и пробирок по ключу k в словарь labs
        elif iss[0].napravleniye.pk not in directions:
            directions += [iss[0].napravleniye.pk]
        n += 1
    if return_type == "directions":
        return JsonResponse(directions, safe=False)

    labs = collections.OrderedDict(sorted(labs.items()))  # Сортировка словаря
    c.setFont('OpenSans', 20)

    paddingx = 17
    data_header = [
        "№", "ФИО, № истории", "№ Напр", "№ емкости", "Тип емкости",
        "Наименования исследований"
    ]
    tw = w - paddingx * 3.5
    tx = paddingx * 2
    ty = 90
    c.setFont('OpenSans', 9)
    styleSheet["BodyText"].fontName = "OpenSans"
    styleSheet["BodyText"].fontSize = 7
    doc_num = 0

    for key in labs:
        doc_num += 1
        p = Paginator(labs[key], perpage)
        i = 0
        if doc_num >= 2:
            c.showPage()

        nn = 0
        gid = "-1"
        for pg_num in p.page_range:
            pg = p.page(pg_num)
            if len(pg) == 0:
                continue
            if pg_num >= 0:
                drawTituls(c,
                           p.num_pages,
                           pg_num,
                           paddingx,
                           lab=lab.title,
                           group=group,
                           otd=key.split("@")[1])
            data = []
            tmp = []
            for v in data_header:
                tmp.append(Paragraph(str(v), styleSheet["BodyText"]))
            data.append(tmp)
            merge_list = {}
            num = 0
            lastid = "-1"
            for obj in pg.object_list:
                tmp = []
                if lastid != obj["tube_id"]:
                    if gid != obj["tube_id"]:
                        i += 1
                    lastid = gid = obj["tube_id"]
                    shownum = True
                else:
                    shownum = False
                    if lastid not in merge_list.keys():
                        merge_list[lastid] = []
                    merge_list[lastid].append(num)
                if shownum:
                    nn += 1
                    tmp.append(
                        Paragraph(str(obj["n"]), styleSheet["BodyText"])
                    )  # "--" if obj["receive_n"] == "0" else obj["receive_n"], styleSheet["BodyText"]))
                    fio = obj["fio"]
                    if obj["history_num"] and len(obj["history_num"]) > 0:
                        fio += ", " + obj["history_num"]
                    tmp.append(Paragraph(fio, styleSheet["BodyText"]))
                    tmp.append(
                        Paragraph(obj["direction"], styleSheet["BodyText"]))
                    tmp.append(
                        Paragraph(obj["tube_id"], styleSheet["BodyText"]))
                    tmp.append(Paragraph(obj["type"], styleSheet["BodyText"]))
                else:
                    tmp.append("")
                    tmp.append("")
                    tmp.append("")
                    tmp.append("")
                    tmp.append("")
                research_tmp = obj["researches"]
                if len(research_tmp) > 44:
                    research_tmp = research_tmp[0:-(len(research_tmp) -
                                                    44)] + "..."
                tmp.append(Paragraph(research_tmp, styleSheet["BodyText"]))

                data.append(tmp)
                num += 1

            style = TableStyle([('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
                                ('INNERGRID', (0, 0), (-1, -1), 0.25,
                                 colors.black),
                                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                                ('LEFTPADDING', (0, 0), (-1, -1), 1),
                                ('RIGHTPADDING', (0, 0), (-1, -1), 1),
                                ('TOPPADDING', (0, 0), (-1, -1), 1),
                                ('BOTTOMPADDING', (0, 0), (-1, -1), 1)])
            for span in merge_list:  # Цикл объединения ячеек
                for pos in range(0, 6):
                    style.add(
                        'INNERGRID', (pos, merge_list[span][0]),
                        (pos, merge_list[span][0] + len(merge_list[span])),
                        0.28, colors.white)
                    style.add(
                        'BOX', (pos, merge_list[span][0]),
                        (pos, merge_list[span][0] + len(merge_list[span])),
                        0.2, colors.black)
            t = Table(data,
                      colWidths=[
                          int(tw * 0.03),
                          int(tw * 0.23),
                          int(tw * 0.09),
                          int(tw * 0.09),
                          int(tw * 0.23),
                          int(tw * 0.35)
                      ],
                      style=style)

            t.canv = c
            wt, ht = t.wrap(0, 0)
            t.drawOn(c, tx, h - ht - ty)
            if pg.has_next():
                c.showPage()
    c.setTitle("Журнал приёма материала - " + lab.title)
    c.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    if group >= 0:
        group_str = directory.ResearchGroup.objects.get(pk=group).title
    elif group == -2:
        group_str = "Все исследования"
    else:
        group_str = "Без группы"

    slog.Log(key="",
             type=25,
             body=json.dumps({
                 "group":
                 group_str,
                 "start":
                 start,
                 "otds": [
                     "%s, %s" %
                     (users.Podrazdeleniya.objects.get(pk=int(x)).title, x)
                     for x in otd
                 ]
             }),
             user=request.user.doctorprofile).save()
    return response
Пример #13
0
def receive_execlist(request):
    import datetime
    import directory.models as directory
    from reportlab.lib.pagesizes import A4
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import landscape
    from reportlab.pdfbase import pdfdoc
    from django.core.paginator import Paginator
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.lib.units import mm
    import os.path
    from io import BytesIO
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.platypus import Table, TableStyle
    from reportlab.lib import colors
    from reportlab.platypus import Paragraph

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf')))
    pdfmetrics.registerFont(
        TTFont('OpenSansB', os.path.join(FONTS_FOLDER, 'OpenSans-Bold.ttf')))

    w, h = landscape(A4)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="execlist.pdf"'
    pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>'
    t = request.GET.get("type", "received")
    researches = json.loads(request.GET["researches"])
    buffer = BytesIO()

    c = canvas.Canvas(buffer, pagesize=landscape(A4))

    marginx = 15 * mm
    marginy = 10 * mm

    pw = w - marginx * 2

    from datetime import timedelta

    if t == "received":
        date = request.GET["date"].split(".")
        date = datetime.date(int(date[2]), int(date[1]), int(date[0]))
        date1 = date
        date2 = date1 + timedelta(days=1)
        dates = request.GET["date"]
    else:
        date1 = request.GET["datestart"].split(".")
        date1 = datetime.date(int(date1[2]), int(date1[1]), int(date1[0]))
        date2 = request.GET["dateend"].split(".")
        date2 = datetime.date(int(date2[2]), int(date2[1]), int(
            date2[0])) + timedelta(days=1)
        if request.GET["datestart"] != request.GET["dateend"]:
            dates = "{} - {}".format(request.GET["datestart"],
                                     request.GET["dateend"])
        else:
            dates = request.GET["datestart"]

    def py(y=0):
        y *= mm
        return h - y - marginy

    def px(x=0):
        x *= mm
        return x + marginx

    def pxr(x=0):
        x *= mm
        return pw - x + marginx

    for pk in researches:
        if directory.Researches.objects.filter(
                pk=pk).exists() and Issledovaniya.objects.filter(
                    research__pk=pk,
                    tubes__time_recive__range=(date1, date2),
                    doc_confirmation__isnull=True).exists():
            research = directory.Researches.objects.get(pk=pk)
            fractions_o = directory.Fractions.objects.filter(
                research=research, hide=False).order_by("sort_weight")
            fractions = [x.title for x in fractions_o]
            if t == "received":
                tubes = [
                    x.pk for x in TubesRegistration.objects.filter(
                        time_recive__range=(date1, date2),
                        doc_recive=request.user.doctorprofile,
                        issledovaniya__research=research).order_by("daynum")
                ]
            else:
                tubes = [
                    x.pk for x in TubesRegistration.objects.filter(
                        time_recive__range=(date1, date2),
                        issledovaniya__doc_confirmation__isnull=True,
                        issledovaniya__research=research).
                    order_by(
                        "issledovaniya__napravleniye__client__individual__family",
                        "issledovaniya__napravleniye__client__individual__name"
                    )
                ]
            pages = Paginator(tubes, 16)
            nn = 0
            for pg_num in pages.page_range:
                c.setFont('OpenSans', 12)
                c.drawString(
                    px(), py(),
                    "Лист исполнения - %s за %s" % (research.title, dates))
                c.drawRightString(pxr(), py(),
                                  research.get_podrazdeleniye().title)
                c.drawString(px(), 6 * mm,
                             "Страница %d из %d" % (pg_num, pages.num_pages))

                styleSheet = getSampleStyleSheet()

                tw = pw

                data = []
                tmp = [
                    Paragraph('<font face="OpenSansB" size="8">№</font>',
                              styleSheet["BodyText"]),
                    Paragraph(
                        '<font face="OpenSansB" size="8">ФИО, № истории<br/>отделение</font>',
                        styleSheet["BodyText"]),
                    Paragraph('<font face="OpenSansB" size="8">№ напр.</font>',
                              styleSheet["BodyText"]),
                    Paragraph('<font face="OpenSansB" size="8">№ мат.</font>',
                              styleSheet["BodyText"]),
                ]
                for fraction in fractions:
                    fraction = fraction[:int(100 / len(fractions))]
                    tmp.append(
                        Paragraph(
                            '<font face="OpenSansB" size="6">%s</font>' %
                            fraction, styleSheet["BodyText"]))
                data.append(tmp)

                pg = pages.page(pg_num)
                for tube_pk in pg.object_list:
                    nn += 1
                    tube = TubesRegistration.objects.get(pk=tube_pk)
                    napravleniye = Issledovaniya.objects.filter(
                        tubes__pk=tube_pk)[0].napravleniye
                    tmp = [
                        Paragraph(
                            '<font face="OpenSans" size="8">%d</font>' %
                            (tube.daynum if t == "received" else nn),
                            styleSheet["BodyText"]),
                        Paragraph(
                            '<font face="OpenSans" size="8">%s</font>' %
                            (napravleniye.client.individual.fio() +
                             ("" if not napravleniye.history_num
                              or napravleniye.history_num == "" else ", " +
                              napravleniye.history_num) + "<br/>" +
                             napravleniye.doc.podrazdeleniye.title),
                            styleSheet["BodyText"]),
                        Paragraph(
                            '<font face="OpenSans" size="8">%d</font>' %
                            napravleniye.pk, styleSheet["BodyText"]),
                        Paragraph(
                            '<font face="OpenSans" size="8">%d</font>' %
                            tube_pk, styleSheet["BodyText"])
                    ]
                    for f in fractions_o:
                        res = Result.objects.filter(
                            fraction=f,
                            issledovaniye__napravleniye=napravleniye)
                        tmp.append(
                            Paragraph(
                                '<font face="OpenSans" size="8">{}</font>'.
                                format("" if t == "received"
                                       or not res.exists() else res[0].value),
                                styleSheet["BodyText"]))
                    data.append(tmp)

                cw = [
                    int(tw * 0.07),
                    int(tw * 0.245),
                    int(tw * 0.055),
                    int(tw * 0.045)
                ]
                lw = tw * 0.615
                for _ in range(0, len(fractions) + 1):
                    cw.append(lw / len(fractions))
                t = Table(data, colWidths=cw)
                t.setStyle(
                    TableStyle([
                        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
                        ('INNERGRID', (0, 0), (-1, -1), 0.8, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.8, colors.black),
                        ('LEFTPADDING', (0, 0), (-1, -1), 2),
                        ('TOPPADDING', (0, 0), (-1, -1), 9),
                        ('TOPPADDING', (1, 0), (1, -1), 3),
                        ('RIGHTPADDING', (0, 0), (-1, -1), 1),
                        ('BOTTOMPADDING', (0, 0), (-1, -1), 9),
                        ('BOTTOMPADDING', (1, 0), (1, -1), 3),
                    ]))
                t.canv = c
                wt, ht = t.wrap(0, 0)
                t.drawOn(c, px(), py(5) - ht)

                c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
Пример #14
0
# Create document 
doc = SimpleDocTemplate(fn_out ,pagesize=letter,
                        rightMargin=0.75*inch,leftMargin=0.75*inch,
                        topMargin=72,bottomMargin=18)
Story = []
t = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
styles.add(ParagraphStyle(name='Small', fontSize=8))
styles.add(ParagraphStyle(name='Smallish', fontSize=9))

####################### Introduction ##############################
# Title
text = 'ICON %s' % (a['data_type'].split('>')[-1][1:])
Story.append(Paragraph(text, styles["Title"]))
Story.append(Spacer(1, 12))

# Error notes
if error_notes:
    for text in error_notes:
        Story.append(Paragraph('<font color="red">%s</font>'%text, styles["Normal"]))
        Story.append(Spacer(1, 4))

# Introduction
text = """
This document describes the data product for %s, which is in NetCDF4 format.
""" % (a['description'])
Story.append(Paragraph(text, styles["Justify"]))
Story.append(Spacer(1, 12))
Пример #15
0
 def encabezado(self):
     p = Paragraph("Compras realizadas durante la semana", self.estiloPC())
     self.story.append(p)
     self.story.append(Spacer(1, 0.5 * inch))
Пример #16
0
    def imprimir(self):

        fec_hoy= datetime.date.today()
        hoy = fec_hoy.strftime("%d/%m/%Y")

        styleSheet=getSampleStyleSheet()
        img=Image("cabezalcaida.png",225,50)
        otro_estilo= ParagraphStyle('',fontSize = 20,textColor = '#000',leftIndent = 200,rightIndent = 50)
        style_barra= ParagraphStyle('',fontSize = 13,textColor = '#000',leftIndent = 300, rightIndent = 0)
        estilo_cabezal= ParagraphStyle('',fontSize = 15,textColor = '#000',leftIndent = 100,rightIndent = 0)

        texto_principal = ""
        estilo_texto = ParagraphStyle('',
                fontSize = 12,
                        alignment = 0,
                        spaceBefore = 0,
                        spaceAfter = 0,
            #backColor = '#fff',
            textColor = '#999',
            leftIndent = 10 )

        h = Paragraph(texto_principal, estilo_texto)
        banner = [ [ img,h ] ]
        options = QFileDialog.Options()
        story=[]
        ban = Table( banner, colWidths=0, rowHeights=10)

        story.append(ban)
        story.append(Spacer(0,15))

        P=Paragraph("<u>Registro de ingresos diarios </u> ",estilo_cabezal)
        story.append(P)
        story.append(Spacer(0,25))

        P=Paragraph("<b>Fecha:  " + str (hoy)+ " </b> ",style_barra)
        story.append(P)
        story.append(Spacer(0,5))

        integrantes = [[Paragraph('''<font size=12> <b> </b></font>''',styleSheet["BodyText"])],
                ['Nombre y Apellido', 'Cuota', 'N° Cuota','Importe', 'Punitorios','Descuento', 'Estado']]
        #pyqtRemoveInputHook()
        #import pdb; pdb.set_trace()

        for item in self.lst_ord:
            integrantes.append([str(item.nombre + ", " + item.apellido),str("cuota credito"),str(item.nro_cuota),str(round(item.monto_cobrado,2)),str(round(item.punitorios,2)), str(round(item.descuento,2)), str(item.estado_cuota)])
            t=Table(integrantes, (120,65, 60, 60,75,75,50))
            t.setStyle(TableStyle([
                               ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
                               ('BOX', (0,1), (-1,-1), 0.25, colors.black),
                               ('BACKGROUND',(0,1),(-1,1),colors.lightgrey)
                               ]))

        story.append(t)
        story.append(Spacer(0,15))


        nombre_archivo = "Reg_ing_diarios" + str(datetime.date.today().year)+"_"+str(datetime.date.today().month) + "_" + str(datetime.date.today().day) + ".pdf"

        #---------------------------------------CAMBIAR RUTA (LA PALABRA slam2016 POR LA RUTA DESEADA DE LA PC)------------------------------------------------#
        file_path ="/home/slam2016/Documentos/credired/credired20170306/pdf/ingresos/ingresos"+str(datetime.date.today().year)+"_"+str(datetime.date.today().month)


        if not os.path.exists(file_path):
            os.makedirs(file_path)

        doc=SimpleDocTemplate(file_path +"/" + nombre_archivo)
        doc.build(story)
        if doc:
            msgBox = QMessageBox()
            msgBox.setWindowTitle("Correcto")
            msgBox.setText( 'Se genero el informe correctamente : ' + nombre_archivo)
            msgBox.exec_()

        if sys.platform == 'linux':
            subprocess.call(["xdg-open", file_path +"/" + nombre_archivo])
        else:
            os.startfile( file_path +"/" + nombre_archivo)
Пример #17
0
	def create_pdf(self):
		"""
		Create a pdf
		"""
		story = []

		doc = SimpleDocTemplate(self.refile, pagesize=A4)
		styles = getSampleStyleSheet()

		spacer = Spacer(0, 0.07 * inch)

		story.append(spacer)
		story.append(spacer)

		ptext = '<font size=10><a>Customer Name: {}</a></font>'.format(self.custo.name)
		story.append(Paragraph(ptext, styles["Normal"]))
		story.append(spacer)

		ptext = '<font size=10><a>Customer Mobile Number: {}</a></font>'.format(
			self.custo.mobile_number)
		story.append(Paragraph(ptext, styles["Normal"]))
		story.append(spacer)

		line = MCLine(-30, 470)
		story.append(line)
		story.append(spacer)

		text_data = ["#", "Maint. Code", "Maint. Product", "Created Date", "Status", "Cost"]
		d = []
		font_size = 8
		centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
		for text in text_data:
			ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
			p = Paragraph(ptext, centered)
			d.append(p)

		data = [d]

		line_num = 1

		formatted_line_data = []

		for val in self.custo.maintenance:
			if val.start_date != None \
					and val.cost_of_bill_of_material != None \
					and val.cost_of_labor != None:
				cost = val.cost_of_bill_of_material + val.cost_of_labor
				line_data = [str(line_num), val.m_code, val.product_of_maintenance,
							 val.created_at, getMaintenanceStatus(val)
					, cost]

				for item in line_data:
					ptext = "<font size=%s>%s</font>" % (font_size - 1, item)
					p = Paragraph(ptext, centered)
					formatted_line_data.append(p)
				data.append(formatted_line_data)
				formatted_line_data = []
				line_num += 1

		table = Table(data, colWidths=[20, 80, 180, 85, 90, 70], rowHeights=20
					  , style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
		story.append(table)
		story.append(spacer)
		#########################################################################################
		simplelistUP = []
		simplelistFN = []
		# mainlist = select_All_maintenance_customer(self.custo.id)
		for mainte in self.custo.maintenance:
			if mainte.start_date != None and mainte.done_date == None \
					and mainte.cost_of_bill_of_material != None \
					and mainte.cost_of_labor != None:
				simplelistUP.append(mainte.cost_of_bill_of_material + mainte.cost_of_labor)
			if mainte.done_date != None and mainte.close_at != None \
					and mainte.cost_of_bill_of_material != None \
					and mainte.cost_of_labor != None:
				simplelistFN.append(mainte.cost_of_bill_of_material + mainte.cost_of_labor)

		bomtxt = '<font size=9><p><b>Maintenance Under Processing Cost</b></p></font>'
		pbomtxt = Paragraph(bomtxt, styles["Normal"])

		bomtxtnum = "<p>{}<p>".format(sum(simplelistUP))
		pbomtxtnum = Paragraph(bomtxtnum, styles["Normal"])

		labtxt = '<font size=9><p><b>Maintenance Finished</b></p></font>'
		plabtxt = Paragraph(labtxt, styles["Normal"])

		labtxtnum = '<p>{}</p>'.format(sum(simplelistFN))
		plabtxtnum = Paragraph(labtxtnum, styles["Normal"])

		totxt = '<font size=9><p><b>Total</b></p></font>'
		ptotxt = Paragraph(totxt, styles["Normal"])

		totxtnum = '<p>{}</p>'.format(sum(simplelistFN) + sum(simplelistUP))
		ptotxtnum = Paragraph(totxtnum, styles["Normal"])
		data = [['', '', '', pbomtxt, pbomtxtnum],
				['', '', '', plabtxt, plabtxtnum],
				['', '', '', ptotxt, ptotxtnum]]
		t = Table(data, colWidths=[5, 5, 250, 170, 60], rowHeights=15)
		t.setStyle(TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
		story.append(t)
		for x in range(10):
			story.append(spacer)
		#
		# #########################################################################################
		actxt = '<font size=11><p><u>Accountant</u><br/>Rani Mohamed</p></font>'
		pactxt = Paragraph(actxt, centered)

		matxtnum = '<font size=11><p><u>Manager</u><br/>Mohamed Althubiti</p></font>'
		pmatxtnum = Paragraph(matxtnum, centered)
		data = [[pactxt, '', '', '', pmatxtnum]]
		t = Table(data, colWidths=[150, 5, 250, 5, 150])
		t.setStyle(TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
		story.append(t)
		#########################################################################################

		story.append(spacer)

		doc.build(story, onFirstPage=self.createDocument, onLaterPages=self.createDocument)

		subprocess.Popen([self.refile], shell=True)
Пример #18
0
    def report(self, context, title):
        # set some characteristics for pdf document
        doc = SimpleDocTemplate(
            self.buffer,
            rightMargin=10,
            leftMargin=10,
            topMargin=20,
            bottomMargin=20,
            pagesize=self.pageSize,
        )

        # a collection of styles offer by the library
        styles = getSampleStyleSheet()

        # add custom paragraph style
        styles.add(
            ParagraphStyle(
                name="Title_Roboto",
                fontName='RobotoBold',
                fontSize=20,
                alignment=TA_CENTER,
            ))
        styles.add(
            ParagraphStyle(name="MainInfo", fontName='RobotoBold',
                           fontSize=12))
        styles.add(
            ParagraphStyle(
                name="TableHeader",
                fontName='RobotoBold',
                fontSize=11,
                alignment=TA_CENTER,
            ))
        styles.add(
            ParagraphStyle(name="MyNormal",
                           fontName='RobotoCondensed-Regular',
                           fontSize=10,
                           leading=12))
        styles.add(
            ParagraphStyle(
                name="MyNormalDecimal",
                fontName='RobotoCondensed-Regular',
                fontSize=10,
                aligment=TA_RIGHT,
            ))
        styles.add(
            ParagraphStyle(name="Categories",
                           fontName='RobotoCondensed-BoldItalic',
                           fontSize=11,
                           leading=12))

        # list used for elements added into document
        data = []
        data.append(Paragraph(title, styles['Title_Roboto']))
        # insert a blank space
        data.append(Spacer(1, 24))

        (data.append(
            Paragraph(
                _('Description') + ': ' + context['trip'].description,
                styles['MainInfo']))) if context['trip'].description else ''
        data.append(Spacer(1, 4))
        data.append(
            Paragraph(
                _('Created by') + ': ' + str(context['trip'].created_by),
                styles['MainInfo']))
        data.append(Spacer(1, 4))
        data.append(
            Paragraph(
                _('Total Cost') + ': ' + str(context['trip'].price),
                styles['MainInfo']))
        data.append(Spacer(1, 12))

        table_data = []
        # table header
        table_data.append([
            Paragraph(_('Category/ No.'), styles['TableHeader']),
            Paragraph(_('Name'), styles['TableHeader']),
            Paragraph(_('Start time'), styles['TableHeader']),
            Paragraph(_('End time'), styles['TableHeader']),
            Paragraph(_('Start point'), styles['TableHeader']),
            Paragraph(_('End point'), styles['TableHeader']),
            Paragraph(_('Means of transport'), styles['TableHeader']),
            Paragraph(_('Address'), styles['TableHeader']),
            Paragraph(_('Cost'), styles['TableHeader'])
        ])
        table_data.append([
            Paragraph(_('Journeys'), styles['Categories']), '', '', '', '', '',
            '', ''
        ])
        for i, journey in enumerate(context['trip'].journey_set.all()):
            if isinstance(journey.start_time, datetime):
                start_time = (journey.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            if isinstance(journey.end_time, datetime):
                end_time = (journey.end_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                end_time = ''
            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                '',
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                Paragraph(formatTableCellData(end_time), styles['MyNormal']),
                Paragraph(formatTableCellData(journey.start_point),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(journey.end_point),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(journey.means_of_transport),
                          styles['MyNormal']),
                '',
                Paragraph(formatTableCellData(journey.price),
                          styles['MyNormalDecimal']),
            ])
        table_data.append([
            Paragraph(_('Accommodations'), styles['Categories']), '', '', '',
            '', '', '', ''
        ])
        for i, accommodation in enumerate(
                context['trip'].accommodation_set.all()):
            if isinstance(accommodation.start_time, datetime):
                start_time = (
                    accommodation.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            if isinstance(accommodation.end_time, datetime):
                end_time = (
                    accommodation.end_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                end_time = ''

            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                Paragraph(formatTableCellData(accommodation.name),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                Paragraph(formatTableCellData(end_time), styles['MyNormal']),
                '',
                '',
                '',
                Paragraph(formatTableCellData(accommodation.address),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(accommodation.price),
                          styles['MyNormalDecimal']),
            ])
        table_data.append([
            Paragraph(_('Attractions'), styles['Categories']), '', '', '', '',
            '', '', ''
        ])
        for i, attraction in enumerate(context['trip'].attraction_set.all()):
            if isinstance(attraction.start_time, datetime):
                start_time = (
                    attraction.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                Paragraph(formatTableCellData(attraction.name),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                '',
                '',
                '',
                '',
                Paragraph(formatTableCellData(attraction.address),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(attraction.price),
                          styles['MyNormalDecimal']),
            ])
        # create table
        trip_details_table = Table(table_data, colWidths=[doc.width / 9.0] * 9)
        trip_details_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)]))
        data.append(trip_details_table)
        data.append(Spacer(1, 12))

        # data.append(Paragraph((_('More info')), styles['MainInfo']))
        data.append(Spacer(1, 4))
        data.append(Paragraph((_('Journeys') + ':'), styles['Categories']))
        for i, journey in enumerate(context['trip'].journey_set.all()):
            if formatTableCellData(journey.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(journey.more_info)),
                              styles['MyNormal']))

        data.append(
            Paragraph((_('Accommodations') + ':'), styles['Categories']))
        for i, accommodation in enumerate(
                context['trip'].accommodation_set.all()):
            if formatTableCellData(accommodation.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(accommodation.more_info)),
                              styles['MyNormal']))

        data.append(Paragraph((_('Attractions') + ':'), styles['Categories']))
        for i, attraction in enumerate(context['trip'].attraction_set.all()):
            if formatTableCellData(attraction.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(attraction.more_info)),
                              styles['MyNormal']))

        # create document
        doc.build(data)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
Пример #19
0
def print_exp_report(request):
    emptype = NonPermanent.objects.select_related().get(parent_id=request.session['matched_employee_id'])
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=exp_report.pdf'
    registerFont(TTFont('DroidSans', os.path.join(settings.MEDIA_ROOT,
                                                  'DroidSans.ttf')))
    registerFont(TTFont('DroidSans-Bold', os.path.join(settings.MEDIA_ROOT,
                                                       'DroidSans-Bold.ttf')))

    doc = SimpleDocTemplate(response, pagesize=A4)
    doc.topMargin = 1.0 * cm
    doc.bottomMargin = 1.0 * cm
    doc.leftMargin = 1.5 * cm
    doc.rightMargin = 1.5 * cm

    elements = []
    logo = os.path.join(settings.MEDIA_ROOT, "logo.png")

    width, height = A4
    head_logo = getSampleStyleSheet()
    head_logo.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                 fontName='DroidSans', fontSize=8))
    heading_style = getSampleStyleSheet()
    heading_style.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                     fontName='DroidSans-Bold',
                                     fontSize=12))
    heading_style.add(ParagraphStyle(name='Spacer', spaceBefore=5,
                                     spaceAfter=5,
                                     fontName='DroidSans-Bold',
                                     fontSize=12))
    signature = getSampleStyleSheet()
    signature.add(ParagraphStyle(name='Center', alignment=TA_CENTER,
                                 fontName='DroidSans', fontSize=10))
    tbl_style = getSampleStyleSheet()

    tbl_style.add(ParagraphStyle(name='Left', alignment=TA_LEFT,
                                 fontName='DroidSans', fontSize=10))
    tbl_style.add(ParagraphStyle(name='Right', alignment=TA_RIGHT,
                                 fontName='DroidSans', fontSize=10))
    tbl_style.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                                 fontName='DroidSans', fontSize=10))

    tbl_style.add(ParagraphStyle(name='BoldLeft', alignment=TA_LEFT,
                                 fontName='DroidSans-Bold', fontSize=10))
    tbl_style.add(ParagraphStyle(name='BoldRight', alignment=TA_RIGHT,
                                 fontName='DroidSans-Bold', fontSize=10))

    tsl = [('ALIGN', (0, 0), (-1, -1), 'CENTER'),
           ('FONT', (0, 0), (-1, 0), 'DroidSans'),
           ('FONTSIZE', (0, 0), (-1, 0), 8),
           ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
           ('TOPPADDING', (0, 0), (-1, -1), 0)]
    tsh = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
           ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]
    ts = [('ALIGN', (1, 1), (-1, -1), 'LEFT'),
          ('FONT', (0, 0), (-1, 0), 'DroidSans'),
          ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
          ('GRID', (0, 0), (-1, -1), 0.5, colors.black)]
    tsf = [('ALIGN', (1, 1), (-1, -1), 'CENTER')]

    im = Image(logo)
    im.drawHeight = 1.25 * cm
    im.drawWidth = 1.25 * cm
    data = []

    date_plus1 = emptype.current_placement().date_to
    data.append([Paragraph(u'Ρόδος, %s / %s / %s' % (date_plus1.day, date_plus1.month, date_plus1.year), tbl_style['Left'])])
    data.append([Paragraph(u' ', heading_style['Spacer'])])
    data.append([Paragraph(u' ', heading_style['Spacer'])])

    data.append([Paragraph(u'Αρ. Πρωτ.: %s' % protocol_number(emptype.order().order_end_manager), tbl_style['Left'])])
    tableh = Table(data, style=tsl, colWidths=[6.0 * cm])
    data = []
    data.append([im, '', ''])
    data.append([Paragraph(u'ΕΛΛΗΝΙΚΗ ΔΗΜΟΚΡΑΤΙΑ', head_logo['Center']), '', ''])
    data.append([Paragraph(u'ΥΠΟΥΡΓΕΙΟ ΠΑΙΔΕΙΑΣ',
                           head_logo['Center']), '', ''])
    data.append([Paragraph(u'ΚΑΙ ΘΡΗΣΚΕΥΜΑΤΩΝ',
                           head_logo['Center']), '', Paragraph(u'Ρόδος, %s / %s / %s' % (date_plus1.day, date_plus1.month, date_plus1.year), tbl_style['Left'])])
    data.append([Paragraph(u'ΠΕΡΙΦΕΡΕΙΑΚΗ ΔΙΕΥΘΥΝΣΗ ΠΡΩΤΟΒΑΘΜΙΑΣ',
                           head_logo['Center']), '', Paragraph(u'Αρ. Πρωτ.: %s' % protocol_number(emptype.order().order_end_manager), tbl_style['Left'])])
    data.append([Paragraph(u'ΚΑΙ ΔΕΥΤΕΡΟΒΑΘΜΙΑΣ ΕΚΠΑΙΔΕΥΣΗΣ ΝΟΤΙΟΥ ΑΙΓΑΙΟΥ',
                           head_logo['Center']), '', ''])
    data.append([Paragraph(u'ΔΙΕΥΘΥΝΣΗ ΔΕΥΤΕΡΟΒΑΘΜΙΑΣ ΕΚΠΑΙΔΕΥΣΗΣ ΔΩΔΕΚΑΝΗΣΟΥ',
                           head_logo['Center']), Paragraph(u'ΠΡΟΣ:', tbl_style['BoldRight']), Paragraph(u'%s %s' % (emptype.lastname, emptype.firstname),
                           tbl_style['BoldLeft'])])
    table0 = Table(data, style=tsl, colWidths=[8.0 * cm, 5.0 * cm, 6.0 * cm])
    elements.append(table0)
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u'Ταχ. Διεύθυνση: %s' % SETTINGS['address'], tbl_style['Left']))
    elements.append(Paragraph(u'Πληροφορίες: %s' % SETTINGS['substitutes_contact_person'], tbl_style['Left']))
    elements.append(Paragraph(u'Τηλέφωνο: %s' % SETTINGS['substitutes_contact_telephone_number'], tbl_style['Left']))
    elements.append(Paragraph(u'Email: %s' % SETTINGS['email_substitutes'], tbl_style['Left']))
    elements.append(Paragraph(u'Fax: %s' % SETTINGS['fax_number'], tbl_style['Left']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'ΘΕΜΑ: Αυτοδίκαιη Απόλυση', tbl_style['BoldLeft']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u'Σας ανακοινώνουμε ότι με την ταυτάριθμη απόφαση της Διεύθυνσης Δευτεροβάθμιας Εκπαίδευσης %s απολύεστε αυτοδίκαια και χωρίς καμία αποζημίωση από το Δημόσιο από τη θέση του/της προσωρινού/ης αναπληρωτή/τριας καθηγητή/τριας την %s/%s/%s.' % (SETTINGS['dide_place'], emptype.current_placement().date_to.day, emptype.current_placement().date_to.month, emptype.current_placement().date_to.year), tbl_style['Justify']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'ΘΕΜΑ: Βεβαίωση Προϋπηρεσίας', tbl_style['BoldLeft']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))
    hours_type = ''

    if emptype.type().id == 1:
        hours_type = u'(23 ώρες την εβδομάδα)'
    elements.append(Paragraph(u'Σας ανακοινώνουμε ότι, όπως προκύπτει από το αρχείο που τηρείται στην υπηρεσία μας, ο/η %s %s με όνομα πατρός %s του κλάδου %s %s τοποθετήθηκε στο %s ως %s %s με σχέση εργασίας ιδιωτικού δικαίου ορισμένου χρόνου και υπηρέτησε από %s/%s/%s έως %s/%s/%s.' % (emptype.lastname, emptype.firstname, emptype.fathername, emptype.profession, emptype.profession.description, emptype.current_placement(), emptype.type(), hours_type, emptype.current_placement().date_from.day,emptype.current_placement().date_from.month,emptype.current_placement().date_from.year, emptype.current_placement().date_to.day, emptype.current_placement().date_to.month,emptype.current_placement().date_to.year), tbl_style['Justify']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'Απόφαση διορισμού %s: %s %s/%s/%s' % (SETTINGS['ministry_title'], emptype.order().order, emptype.order().date.day, emptype.order().date.month, emptype.order().date.year), tbl_style['Left']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'Απόφαση τοποθέτησης Διευθυντή Δ.Ε. Δωδεκανήσου: %s' % emptype.order().order_start_manager, tbl_style['Left']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'Απόφαση απόλυσης Διευθυντή Δ.Ε. Δωδεκανήσου: %s' % emptype.order().order_end_manager, tbl_style['Left']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    if emptype.current_placement().substituteplacement.date_from_show:
        elements.append(Paragraph(u'Ημερομηνία ανάληψης υπηρεσίας: %s/%s/%s' % (emptype.current_placement().substituteplacement.date_from_show.day, emptype.current_placement().substituteplacement.date_from_show.month, emptype.current_placement().substituteplacement.date_from_show.year), tbl_style['Left']))
    else:
        elements.append(Paragraph(u'Ημερομηνία ανάληψης υπηρεσίας: %s/%s/%s' % (emptype.current_placement().date_from.day, emptype.current_placement().date_from.month, emptype.current_placement().date_from.year), tbl_style['Left']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))


    elements.append(Paragraph(u'Χρόνος προϋπηρεσίας για μισθολογικό κλιμάκιο: %s' % emptype.experience_salary(), tbl_style['Left']))

    elements.append(Paragraph(u'Χρόνος προϋπηρεσίας για πίνακες αναπληρωτών: %s' % emptype.experience(), tbl_style['Left']))
#    if emptype.current_placement().substituteplacement.date_from_show:
#        elements.append(Paragraph(u'Χρόνος προϋπηρεσίας για μισθολογικό κλιμάκιο: %s/%s/%s - %s/%s/%s' % (emptype.current_placement().substituteplacement.date_from_show.day, emptype.current_placement().substituteplacement.date_from_show.month, emptype.current_placement().substituteplacement.date_from_show.year, emptype.current_placement().date_to.day, emptype.current_placement().date_to.month, emptype.current_placement().date_to.year), tbl_style['Left']))
#    else:
#        elements.append(Paragraph(u'Χρόνος προϋπηρεσίας για μισθολογικό κλιμάκιο: %s/%s/%s - %s/%s/%s' % (emptype.current_placement().date_from.day, emptype.current_placement().date_from.month, emptype.current_placement().date_from.year, emptype.current_placement().date_to.day, emptype.current_placement().date_to.month, emptype.current_placement().date_to.year), tbl_style['Left']))


#    elements.append(Paragraph(u'Χρόνος προϋπηρεσίας για πίνακες αναπληρωτών:  %s/%s/%s - %s/%s/%s' % (emptype.current_placement().date_from.day, emptype.current_placement().date_from.month, emptype.current_placement().date_from.year, emptype.current_placement().date_to.day, emptype.current_placement().date_to.month, emptype.current_placement().date_to.year), tbl_style['Left']))
    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'Το πλήρες ωράριο εβδομαδιαίας διδακτικής απασχόλησης των εκπαιδευτικών της Δευτεροβάθμιας Εκπαίδευσης κλάδων ΠΕ που ισχύει σύμφωνα με τον Ν.4152/2013 είναι 23 ώρες.', tbl_style['Justify']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    elements.append(Paragraph(u'Η βεβαίωση αυτή χορηγείται ύστερα από αίτηση του/της ενδιαφερόμενου/ης προκειμένου να τη χρησιμοποιήσει ως δικαιολογητικό για την αναγνώριση της προϋπηρεσίας του/της.', tbl_style['Justify']))

    elements.append(Paragraph(u' ', heading_style['Spacer']))

    data = []
    sign = os.path.join(settings.MEDIA_ROOT, "signature.png")
    im = Image(sign)
    im.drawHeight = 3.2 * cm
    im.drawWidth = 6.5 * cm

    data.append([Paragraph(u' ', signature['Center']) ,im])

    table6 = Table(data, style=tsf, colWidths=[10.0 * cm, 7.0 * cm])
    elements.append(table6)

    if emptype.order().order_type == 3:
        logo = os.path.join(settings.MEDIA_ROOT, "espa2.jpg")
        im = Image(logo)
        im.drawHeight = 3.0 * cm
        im.drawWidth = 16.3 * cm
        elements.append(im)

    elements.append(PageBreak())

    doc.build(elements)
    return response
Пример #20
0
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"]),
                exercise['setting_text']
            ] + [''] * 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)
Пример #21
0
 def make_paragraph(self, text, style=None):
     """Uses the Paragraph class to return a new paragraph object"""
     return Paragraph(text, style)
Пример #22
0
def draw_text(report, text, attributes):
    """
    Draw text string on report_info.
    :param report:
    :param text: text to output to report_info
    :param attributes: attributes (e.g. 'font name', 'font size', 'color') to apply to text
    """
    report['canvas'].saveState()

    text = format_text(text, attributes)
    styles = getSampleStyleSheet()

    text_alignment = {'Left': TA_LEFT, 'Center': TA_CENTER, 'Right': TA_RIGHT, 'Justified': TA_JUSTIFY}
    base_style = styles['Normal']
    left_indent = attributes.get("leftIndent", base_style.leftIndent)
    right_indent = attributes.get("rightIndent", base_style.leftIndent)
    font_name = get_font(report, attributes, base_style)

    font_is_bold = convert2boolean(attributes.get('fontIsBold'))
    if font_is_bold:
        text = '<b>' + text + '</b>'
    font_is_italic = convert2boolean(attributes.get('fontIsItalic'))
    if font_is_italic:
        text = '<i>' + text + '</i>'

    font_is_underline = convert2boolean(attributes.get('fontIsUnderline'))
    if font_is_underline:
        text = '<u>' + text + '</u>'
    font_is_strike_through = convert2boolean(attributes.get('fontIsStrikeThrough'))
    if font_is_strike_through:
        text = '<strike>' + text + '</strike>'

    font_size = attributes.get('fontSize', 10)
    text_color = attributes.get('forecolor')
    if text_color is None:
        text_color = base_style.textColor
    else:
        text_color = colors.HexColor(text_color)

    ps = ParagraphStyle(name='cell',
                        parent=styles['Normal'],
                        fontName=font_name,
                        fontSize=font_size,
                        leading=font_size * 1.2,
                        leftIndent=left_indent,
                        rightIndent=right_indent,
                        alignment=text_alignment[attributes.get('textAlignment', 'Left')],
                        textColor=text_color
                        )
    # text = "<br/>".join(str(text).split('\n'))   # replace '\n' with a <br/> to cause newline
    text = str(text).replace('\n', '<br/>')
    # story = [Paragraph(str(text), ps)]
    story = [Paragraph(text, ps)]
    story_in_frame = KeepInFrame(attributes['width'], attributes['height'], story, mode='shrink')   # 'truncate, overflow, shrink

    data = [[story_in_frame]]
    t = Table(data, colWidths=attributes['width'], rowHeights=attributes['height'])

    table_style = TableStyle([
                            ('VALIGN', (0,0),(0,0), attributes.get('verticalAlignment', 'TOP').upper()),
                            ('TEXTCOLOR', (0, 0), (0, 0), colors.black),
                            ('LEFTPADDING', (0, 0), (0, 0), 0),
                            ('RIGHTPADDING', (0, 0), (0, 0), 0),
                            ('TOPPADDING', (0, 0), (0, 0), 0),
                            ('BOTTOMPADDING', (0, 0), (0, 0), 0),
                            ])
    if attributes.get('mode') is not None:
        backcolor = attributes.get('backcolor')
        if backcolor is not None:
            table_style.add('BACKGROUND', (0, 0), (0, 0), colors.HexColor(backcolor))

    t.setStyle(table_style)
    t.wrapOn(report['canvas'], attributes['width'], attributes['height'])
    t.drawOn(report['canvas'], attributes['x'], report['cur_y'] - attributes['y'] - attributes['height'])

    report['canvas'].restoreState()
Пример #23
0
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/pdf')
        buff = BytesIO()
        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                rightMargin=40,
                                leftMargin=40,
                                topMargin=60,
                                bottomMargin=30,
                                title='REFERENCIA OXXO')
        items = []

        stylo_p_center = ParagraphStyle('parrafo_center',
                                        alignment=TA_CENTER,
                                        fontSize=11,
                                        fontName="Times-Roman")
        stylo_p_derecha = ParagraphStyle('parrafo_center',
                                         alignment=TA_RIGHT,
                                         fontSize=11,
                                         fontName="Times-Roman")
        stylo_p_izquierda = ParagraphStyle('parrafo_center',
                                           alignment=TA_LEFT,
                                           fontSize=12,
                                           fontName="Times-Roman")
        stylo_p_center_INFO = ParagraphStyle('parrafo_center',
                                             alignment=TA_CENTER,
                                             fontSize=8,
                                             fontName="Times-Roman")
        stylo_p = ParagraphStyle('parrafo',
                                 alignment=TA_LEFT,
                                 fontSize=18,
                                 fontName="Times-Roman")
        stylo_titulo = ParagraphStyle('titulo',
                                      alignment=TA_CENTER,
                                      fontSize=14,
                                      fontName="Times-Bold")
        stylo_titulo_normal = ParagraphStyle('titulo',
                                             alignment=TA_CENTER,
                                             fontSize=14,
                                             fontName="Times-Roman")
        stylo_portada_title = ParagraphStyle('titulo',
                                             alignment=TA_CENTER,
                                             fontSize=20,
                                             fontName="Times-Bold")

        ord_object = Orden.objects.get(ord_order_id=self.kwargs['ord'])

        dta = []

        items.append(
            Image(os.path.realpath('static/img/oxxopay1.jpg'), 8 * cm, 5 * cm))
        text = """MONTO A PAGAR"""
        items.append(Paragraph(text, stylo_titulo))
        items.append(Spacer(0, 10))

        text = """${} MXN""".format(intcomma(ord_object.ord_monto))
        items.append(Paragraph(text, stylo_titulo_normal))
        items.append(Spacer(0, 10))

        text = """OXXO Cobra una comision al momento de realizar el pago"""
        items.append(Paragraph(text, stylo_titulo_normal))
        items.append(Spacer(0, 20))

        text = """REFERENCIA"""
        items.append(Paragraph(text, stylo_p))
        items.append(Spacer(0, 20))

        text = """{}""".format(ord_object.ord_referencia)
        items.append(Paragraph(text, stylo_portada_title))
        items.append(Spacer(0, 15))
        items.append(Image(ord_object.ord_barcode_url, 5 * cm, 1.5 * cm))
        items.append(Spacer(0, 30))

        text = """INSTRUCCIONES"""
        items.append(Paragraph(text, stylo_titulo))
        items.append(Spacer(0, 20))

        text = """1. Acude a la tienda OXXO más cercana."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """2. Indica en caja que quieres realizar un pago de OXXOPay"""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """3. Dicta al cajero el número de referencia en esta ficha para que tecleé directamente en la pantalla de venta."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """4. Realiza el pago correspondiente con dinero en efectivo."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """5. Al confirmar tu pago, el cajero te entregará un comprobante impreso. En el podrás verificar que se haya realizado correctamente.Conserve este comprobante de pago."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        # data_table = [(
        #     Image(os.path.realpath('static/img/OXXO.png'), 5*cm, 5*cm),
        #     Paragraph(text, stylo_p),
        #     )]

        # tabla = Table(data_table, colWidths=[
        #     15 * cm,
        #     5 * cm,
        #     ])

        # tabla.setStyle(TableStyle(
        #     [
        #         ('GRID', (0, 0), (-1, -1), 1, colors.black),
        #         # ('LINEBELOW', (0, 0), (-1, 0), 0, colors.darkblue),
        #         ('BACKGROUND', (0, 0), (-1, 0), colors.transparent)
        #     ]
        # ))

        # items.append(tabla)

        # items.append(Paragraph("FICHA DIGITAL NOES NECESARIO IMPRIMIR", stylo_titulo))

        # items.append(Spacer(0, 20))

        doc.build(items,
                  onFirstPage=self.myFirstPage,
                  onLaterPages=self.myLaterPages)
        response.write(buff.getvalue())
        buff.close()
        return response
Пример #24
0
def generar_pdf(request):
    #print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Empresa_Datos_Formales.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    response['Content-Disposition'] = 'attachment; filename=Empresa_Datos_Formales.pdf' #% pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=landscape(A4),
                            rightMargin=10,
                            leftMargin=10,
                            topMargin=60,
                            bottomMargin=18,
                            )
    datos = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Empresa", styles['Normal'])
    datos.append(header)
    headings = (        'raz_soc',
                        'nom_com',
                        'rut',
                        'num_bps',
                        'num_mtss',
                        'dom_cons',
                        'dom_fis',
                        'tel',
                        'email',
                        'celular',
                        'c_giro_c',
                        'nom_giro',
                        'f_bal',
                        'tipo' )
    alldatos = [(p.razon_social,
                        p.nombre_comercial,
                        p.rut,
                        p.num_bps,
                        p.num_mtss,
                        p.domicilio_constituido,
                        p.domicilio_fiscal,
                        p.telefono,
                        p.email,
                        p.celular,
                        p.cod_giro_ciiu,
                        p.nombre_giro,
                        p.fecha_balance,
                        p.tipo ) for p in Empresa_Datos_Formales.objects.all()]

    print (alldatos)

    t = Table([headings] + alldatos, colWidths=60, rowHeights=50, style=None )
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    datos.append(t)
    doc.build(datos)
    response.write(buff.getvalue())
    buff.close()
    return response
Пример #25
0
 def _include_header(self) -> None:
     ptext = '<font size=18>Hashtag Report</font>'
     self.report_data.append(Paragraph(ptext, self.styles["Center"]))
     self.report_data.append(Spacer(1, 24))
Пример #26
0
    # ('TEXTCOLOR',(0,0),(1,-1),colors.red),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    # ('INNERGRID', (0,0),(-1,-1), 0.25, colors.black),
    # ('BOX', (0,0), (-1,-1), 0.5, colors.black),
    ('GRID', (0, 0), (-1, -1), 1, colors.black),
    ('FONTSIZE', (0, 0), (-1, -1), 10),
    ('FONT', (0, 0), (-1, -1), 'msyh'),
    ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
    ('TOPPADDING', (0, 0), (-1, -1), 2)
]
TAB_STY_LST.extend(TAB_STYLE)
# 生成表格样式
TAB_STY = TableStyle(TAB_STY_LST)
# 生成页眉和页脚段落
TITLE_PARA = Paragraph(("&nbsp;" * 2).join("2018年泗县中考体育考试异常情况登记表"),
                       stylesheet['Title'])
FOOT_PARA = Paragraph(FOOT_TEXT, stylesheet['Normal'])


# 生成每页元素
def gen_page_elmnts(pdatas,
                    group_num,
                    sch='泗县一中',
                    group_name='女',
                    test_date='4月21日上午'):
    page_elmnts = []
    page_elmnts.append(TITLE_PARA)
    title_text_sch = "考点:{}".format(sch)
    title_text_group = "组别:{} {}子组".format(group_num, group_name)
    title_text_date = ''.join(
        (str(datetime.datetime.today().year), '年', test_date))
Пример #27
0
def convert_html_to_reportlab(pdf, text):
    # parsing and replacing not supported html tags for reportlab...
    soup = BeautifulSoup(text, "html5lib")

    # number ol list elements
    ols = soup.find_all('ol')
    for ol in ols:
        counter = 0
        for li in ol.children:
            if li.name == 'li':
                # if start attribute is available set counter for first list element
                if li.parent.get('start') and not li.find_previous_sibling():
                    counter = int(ol.get('start'))
                else:
                    counter += 1
                if li.get('value'):
                    counter = li.get('value')
                else:
                    li['value'] = counter

    # read all list elements...
    for element in soup.find_all('li'):
        # ... and replace ul list elements with <para><bullet>&bull;</bullet>...<para>
        if element.parent.name == "ul":
            # nested lists
            if element.ul or element.ol:
                for i in element.find_all('li'):
                    element.insert_before(i)
                element.clear()
            else:
                element.name = "para"
                bullet_tag = soup.new_tag("bullet")
                bullet_tag.string = u"•"
                element.insert(0, bullet_tag)
        # ... and replace ol list elements with <para><bullet><seqreset id="%id" base="value"><seq id="%id"></seq>.</bullet>...</para>
        if element.parent.name == "ol":
            counter = None
            # set list id if element is the first of numbered list
            if not element.find_previous_sibling():
                id = random.randrange(0, 101)
                if element.parent.get('start'):
                    counter = element.parent.get('start')
            if element.get('value'):
                counter = element.get('value')
            # nested lists
            if element.ul or element.ol:
                nested_list = element.find_all('li')
                for i in reversed(nested_list):
                    element.insert_after(i)

            element.attrs = {}
            element.name = "para"
            element.insert(0, soup.new_tag("bullet"))
            element.bullet.insert(0, soup.new_tag("seq"))
            element.bullet.seq['id'] = id
            if counter:
                element.bullet.insert(0, soup.new_tag("seqreset"))
                element.bullet.seqreset['id'] = id
                element.bullet.seqreset['base'] = int(counter) - 1
            element.bullet.insert(2, ".")
    # remove tags which are not supported by reportlab (replace tags with their children tags)
    for tag in soup.find_all('ul'):
        tag.unwrap()
    for tag in soup.find_all('ol'):
        tag.unwrap()
    for tag in soup.find_all('li'):
        tag.unwrap()

    # use tags which are supported by reportlab
    # replace <s> to <strike>
    for tag in soup.find_all('s'):
        tag.name = "strike"

    # replace <del> to <strike>
    for tag in soup.find_all('del'):
        tag.name = "strike"

    for tag in soup.find_all('a'):
        # remove a tags without href attribute
        if not tag.get('href'):
            tag.extract()
    for tag in soup.find_all('img'):
        # remove img tags without src attribute
        if not tag.get('src'):
            tag.extract()

    # replace style attributes in <span> tags
    for tag in soup.find_all('span'):
        if tag.get('style'):
            # replace style attribute "text-decoration: line-through;" to <strike> tag
            if 'text-decoration: line-through' in str(tag['style']):
                strike_tag = soup.new_tag("strike")
                strike_tag.string = tag.string
                tag.replace_with(strike_tag)
            # replace style attribute "text-decoration: underline;" to <u> tag
            elif 'text-decoration: underline' in str(tag['style']):
                u_tag = soup.new_tag("u")
                u_tag.string = tag.string
                tag.replace_with(u_tag)
            # replace style attribute "color: #xxxxxx;" to "<font backcolor='#xxxxxx'>...</font>"
            elif 'background-color: ' in str(tag['style']):
                font_tag = soup.new_tag("font")
                color = re.findall('background-color: (.*?);',
                                   str(tag['style']))
                if color:
                    font_tag['backcolor'] = color
                if tag.string:
                    font_tag.string = tag.string
                tag.replace_with(font_tag)
            # replace style attribute "color: #xxxxxx;" to "<font color='#xxxxxx'>...</font>"
            elif 'color: ' in str(tag['style']):
                font_tag = soup.new_tag("font")
                color = re.findall('color: (.*?);', str(tag['style']))
                if color:
                    font_tag['color'] = color
                if tag.string:
                    font_tag.string = tag.string
                tag.replace_with(font_tag)
            else:
                tag.unwrap()
        else:
            tag.unwrap()
    # print paragraphs with numbers
    text = soup.body.contents
    paragraph_number = 1
    for paragraph in text:
        paragraph = str(paragraph)
        # ignore empty paragraphs (created by newlines/tabs of ckeditor)
        if paragraph == '\n' or paragraph == '\n\n' or paragraph == '\n\t':
            continue
        if "<pre>" in paragraph:
            txt = paragraph.replace('\n', '<br/>').replace(' ', '&nbsp;')
            if config["motions_pdf_paragraph_numbering"]:
                pdf.append(
                    Paragraph(txt, stylesheet['InnerMonotypeParagraph'],
                              str(paragraph_number)))
                paragraph_number += 1
            else:
                pdf.append(Paragraph(txt,
                                     stylesheet['InnerMonotypeParagraph']))
        elif "<para>" in paragraph:
            pdf.append(Paragraph(paragraph, stylesheet['InnerListParagraph']))
        elif "<seqreset" in paragraph:
            pass
        elif "<h1>" in paragraph:
            pdf.append(Paragraph(paragraph, stylesheet['InnerH1Paragraph']))
        elif "<h2>" in paragraph:
            pdf.append(Paragraph(paragraph, stylesheet['InnerH2Paragraph']))
        elif "<h3>" in paragraph:
            pdf.append(Paragraph(paragraph, stylesheet['InnerH3Paragraph']))
        else:
            if config["motions_pdf_paragraph_numbering"]:
                pdf.append(
                    Paragraph(paragraph, stylesheet['InnerParagraph'],
                              str(paragraph_number)))
                paragraph_number += 1
            else:
                pdf.append(Paragraph(paragraph, stylesheet['InnerParagraph']))
from reportlab.platypus import (Paragraph, SimpleDocTemplate, Spacer)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from custom_graph.CanvasFigure import CanvasFigure

doc = SimpleDocTemplate("ignore/custom_graph.pdf", pagesize=letter)
style = getSampleStyleSheet()
story = []
p = Paragraph("This is a table. " * 10, style['Normal'])
story.append(p)
dataX = [1, 2, 3, 4, 5]
dataY = [1, 2, 3, 4, 5]
graph = CanvasFigure(dataX, dataY, width=500, height=250)
story.append(graph)
story.append(p)
s = Spacer(width=0, height=60)
doc.build(story)
Пример #29
0
IAGi = Image(os.path.join(data_dirA, "fig3GI.png"))
IAGi._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)

IBC = Image(os.path.join(data_dirB, "fig3Cont.png"))
IBC._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)
IBGi = Image(os.path.join(data_dirB, "fig3GI.png"))
IBGi._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.1 * inch) / 2)

IO = Image(os.path.join(supAlPath, "Figure_3.jpg"))
IO._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch))

myTable = Table([[IO, [IAC, IAGi], [IBC, IBGi]]], spaceAfter=inch * 0.1)
myTable.setStyle(
    TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
fig3par = Paragraph("fig 3:", style=styles["Normal"])
story.append(fig3par)
story.append(myTable)

IANAD = Image(os.path.join(data_dirA, "fig4NAD.png"))
IANAD._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch) / 2)
IAPGC = Image(os.path.join(data_dirA, "fig4PGC1a_d.png"))
IAPGC._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch) / 2)

IBNAD = Image(os.path.join(data_dirB, "fig4NAD.png"))
IBNAD._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch) / 2)
IBPGC = Image(os.path.join(data_dirB, "fig4PGC1a_d.png"))
IBPGC._restrictSize((PW - 2.1 * inch) / 3, (PH - 2.3 * inch) / 2)

IO = Image(os.path.join(supAlPath, "Temporal_Figure_4.jpg"))
IO._restrictSize((PW - 2.1 * inch) / 3, PH - 2.3 * inch)
Пример #30
0
def export_pdf(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of a nutrition plan

    See also
    * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
    * http://www.reportlab.com/apis/reportlab/dev/platypus.html
    '''

    # Load the plan
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            plan = get_object_or_404(NutritionPlan, pk=id)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)

    plan_data = plan.get_nutritional_values()

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            title=_('Nutrition plan'),
                            author='wger Workout Manager',
                            subject=_('Nutritional plan %s') % request.user.username)

    # Background colour for header
    # 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)

    # container for the 'Flowable' objects
    elements = []
    data = []

    # Iterate through the Plan
    meal_markers = []
    ingredient_markers = []

    # Meals
    i = 0
    for meal in plan.meal_set.select_related():
        i += 1

        meal_markers.append(len(data))

        if not meal.time:
            p = Paragraph(u'<para align="center"><strong>{nr} {meal_nr}</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i),
                          styleSheet["Normal"])
        else:
            p = Paragraph(u'<para align="center"><strong>'
                          u'{nr} {meal_nr} - {meal_time}'
                          u'</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i, meal_time=meal.time.strftime("%H:%M")),
                          styleSheet["Normal"])
        data.append([p])

        # Ingredients
        for item in meal.mealitem_set.select_related():
            ingredient_markers.append(len(data))

            p = Paragraph(u'<para>{0}</para>'.format(item.ingredient.name), styleSheet["Normal"])
            if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:
                unit_name = 'g'
            else:
                unit_name = ' ' + item.weight_unit.unit.name

            data.append([Paragraph(u"{0}{1}".format(item.amount, unit_name), styleSheet["Normal"]),
                         p])

    # Set general table styles
    table_style = []

    # Set specific styles, e.g. background for title cells
    for marker in meal_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)))

    # has the plan any data?
    if data:
        t = Table(data, style=table_style)

        # Manually set the width of the columns
        t._argW[0] = 2.5 * cm

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

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

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

    # append the table to the document
    elements.append(t)
    elements.append(Paragraph('<para>&nbsp;</para>', styleSheet["Normal"]))

    # Create table with nutritional calculations
    data = []
    data.append([Paragraph(u'<para align="center">{0}</para>'.format(_('Nutritional data')),
                 styleSheet["Bold"])])
    data.append([Paragraph(_('Macronutrients'), styleSheet["Normal"]),
                 Paragraph(_('Total'), styleSheet["Normal"]),
                 Paragraph(_('Percent of energy'), styleSheet["Normal"]),
                 Paragraph(_('g per body kg'), styleSheet["Normal"])])
    data.append([Paragraph(_('Energy'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['energy']), styleSheet["Normal"])])
    data.append([Paragraph(_('Protein'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['protein']), styleSheet["Normal"])])
    data.append([Paragraph(_('Carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['carbohydrates']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Sugar content in carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates_sugar']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fat'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['fat']), styleSheet["Normal"])])
    data.append([Paragraph(_('Saturated fat content in fats'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat_saturated']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fibres'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fibres']), styleSheet["Normal"])])
    data.append([Paragraph(_('Sodium'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['sodium']), styleSheet["Normal"])])

    table_style = []
    table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black))
    table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black))
    table_style.append(('SPAN', (0, 0), (-1, 0)))  # Title
    table_style.append(('SPAN', (1, 2), (-1, 2)))  # Energy
    table_style.append(('SPAN', (1, 5), (-1, 5)))  # Sugar
    table_style.append(('SPAN', (1, 7), (-1, 7)))  # Saturated fats
    table_style.append(('SPAN', (1, 8), (-1, 8)))  # Fibres
    table_style.append(('SPAN', (1, 9), (-1, 9)))  # Sodium
    t = Table(data, style=table_style)
    t._argW[0] = 5 * cm
    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('nutrition:plan:view', kwargs={'id': plan.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)
    doc.build(elements)

    response['Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf'
    response['Content-Length'] = len(response.content)
    return response