def _build_recap(_recap_date, _recap_ref, recaps):
    """
    """
    elements = []

    _intro = Table([[
        "Veuillez trouver ci-joint le r" + u"é" +
        "capitulatif des factures ainsi que le montant total " + u"à" +
        " payer"
    ]], [10 * cm, 5 * cm],
                   1 * [0.5 * cm],
                   hAlign='LEFT')
    elements.append(_intro)
    elements.append(Spacer(1, 18))

    data = []
    i = 0
    data.append(("N d'ordre", u"Note no°", u"Nom et prénom", "Montant"))
    total = 0.0
    _invoice_nrs = ""
    for recap in recaps:
        i += 1
        data.append((i, recap[0], recap[1], recap[2]))
        total = decimal.Decimal(total) + decimal.Decimal(recap[2])
        _invoice_nrs += "-" + recap[0]
    data.append(("", "", u"à reporter", round(total, 2), ""))

    table = Table(data, [2 * cm, 3 * cm, 7 * cm, 3 * cm],
                  (i + 2) * [0.75 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    elements.append(table)

    elements.append(Spacer(1, 18))

    elements.append(Spacer(1, 18))
    _infos_iban = Table([[
        "Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" +
        "rence: %s " % _recap_ref
    ]], [10 * cm],
                        1 * [0.5 * cm],
                        hAlign='LEFT')
    _date_infos = Table([["Date facture : %s " % _recap_date]], [10 * cm],
                        1 * [0.5 * cm],
                        hAlign='LEFT')

    elements.append(_date_infos)
    elements.append(Spacer(1, 18))
    elements.append(_infos_iban)
    elements.append(Spacer(1, 18))
    _total_a_payer = Table(
        [["Total " + u"à" + " payer:",
          "%10.2f Euros" % total]], [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    _infos_iban = Table(
        [["Num" + u"é" + "ro compte IBAN: LU55 0019 4555 2516 1000 BCEELULL"]],
        [10 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_infos_iban)

    return elements
예제 #2
0
delta = 1 * cm
epsilon = 0.5 * cm

defaultLevelStyles = [
    ParagraphStyle(name='Level 0',
                   fontName=_baseFontName,
                   fontSize=10,
                   leading=11,
                   firstLineIndent=0,
                   leftIndent=epsilon)
]

defaultTableStyle = \
    TableStyle([
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('RIGHTPADDING', (0,0), (-1,-1), 0),
        ('LEFTPADDING', (0,0), (-1,-1), 0),
    ])


class TableOfContents(IndexingFlowable):
    """This creates a formatted table of contents.

    It presumes a correct block of data is passed in.
    The data block contains a list of (level, text, pageNumber)
    triplets.  You can supply a paragraph style for each level
    (starting at zero).
    Set dotsMinLevel to determine from which level on a line of
    dots should be drawn between the text and the page number.
    If dotsMinLevel is set to a negative value, no dotted lines are drawn.
    """
예제 #3
0
    def draw_footer(self, y_pos):
        """
        Draws the footer.
        """

        para_style = getSampleStyleSheet()['Normal']
        para_style.fontSize = 8

        footer_para = Paragraph(self.footer_text.replace("\n", "<br/>"),
                                para_style)
        disclaimer_para = Paragraph(
            self.disclaimer_text.replace("\n", "<br/>"), para_style)
        billing_address_para = Paragraph(
            self.billing_address_text.replace("\n", "<br/>"), para_style)

        footer_data = [['', footer_para], [(_('Billing Address')), ''],
                       ['', billing_address_para], [(_('Disclaimer')), ''],
                       ['', disclaimer_para]]

        footer_style = [
            # Styling for the entire footer table.
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('TEXTCOLOR', (0, 0), (-1, -1), '#AAAAAA'),

            # Billing Address Header styling
            ('LEFTPADDING', (0, 1), (0, 1), 5 * mm),

            # Disclaimer Header styling
            ('LEFTPADDING', (0, 3), (0, 3), 5 * mm),
            ('TOPPADDING', (0, 3), (0, 3), 2 * mm),

            # Footer Body styling
            # ('BACKGROUND', (1, 0), (1, 0), '#EEEEEE'),

            # Billing Address Body styling
            ('BACKGROUND', (1, 2), (1, 2), '#EEEEEE'),

            # Disclaimer Body styling
            ('BACKGROUND', (1, 4), (1, 4), '#EEEEEE'),
        ]

        if self.is_invoice:
            terms_conditions_para = Paragraph(
                self.terms_conditions_text.replace("\n", "<br/>"), para_style)
            footer_data.append([(_('TERMS AND CONDITIONS')), ''])
            footer_data.append(['', terms_conditions_para])

            # TERMS AND CONDITIONS header styling
            footer_style.append(('LEFTPADDING', (0, 5), (0, 5), 5 * mm))
            footer_style.append(('TOPPADDING', (0, 5), (0, 5), 2 * mm))

            # TERMS AND CONDITIONS body styling
            footer_style.append(('BACKGROUND', (1, 6), (1, 6), '#EEEEEE'))

        footer_table = Table(footer_data, [5 * mm, 176 * mm])

        footer_table.setStyle(TableStyle(footer_style))
        __, rendered_height = footer_table.wrap(0, 0)

        if y_pos - (self.margin + self.min_clearance) <= rendered_height:
            self.prepare_new_page()

        footer_table.drawOn(self.pdf, self.margin, self.margin + 5 * mm)
예제 #4
0
def HeaderFooterTrans(canvas, doc):
    canvas.saveState()
    title = "Reporte de Transacciones"
    canvas.setTitle(title)

    Story = []
    styles = getSampleStyleSheet()

    archivo_imagen = finders.find('assets/img/logo.jpg')
    canvas.drawImage(archivo_imagen,
                     30,
                     720,
                     width=540,
                     height=100,
                     preserveAspectRatio=True)

    fecha = datetime.now().strftime('%d/%m/%Y ')
    # Estilos de Párrafos
    ta_c = ParagraphStyle(
        'parrafos',
        alignment=TA_CENTER,
        fontSize=10,
        fontName="Helvetica",
    )
    ta_l = ParagraphStyle(
        'parrafos',
        alignment=TA_LEFT,
        fontSize=13,
        fontName="Helvetica-Bold",
    )
    ta_l7 = ParagraphStyle(
        'parrafos',
        alignment=TA_LEFT,
        fontSize=7,
        fontName="Helvetica-Bold",
    )
    ta_r = ParagraphStyle(
        'parrafos',
        alignment=TA_CENTER,
        fontSize=11,
        fontName="Helvetica-Bold",
    )

    # Header
    header = Paragraph(
        "REPORTE DE TRANSACCIONES ",
        ta_l,
    )
    w, h = header.wrap(doc.width + 250, doc.topMargin)
    header.drawOn(canvas, 215, doc.height - 10 + doc.topMargin - 80)

    total1 = Paragraph(
        "Total: " + str(total) + " bs.",
        ta_l,
    )
    w, h = total1.wrap(doc.width + 250, doc.topMargin)
    total1.drawOn(canvas, 425, doc.height - 10 + doc.topMargin - 60)

    meses = Paragraph(
        "Mes: " + str(mes1) + ".",
        ta_l,
    )
    w, h = meses.wrap(doc.width + 250, doc.topMargin)
    meses.drawOn(canvas, 75, doc.height - 10 + doc.topMargin - 60)

    #header1 = Paragraph("<u>DIRECCIÓN DE AGRICULTURA Y TIERRA</u> ",ta_r,)
    #w,h = header1.wrap(doc.width-115, doc.topMargin)
    #header1.drawOn(canvas, 140, doc.height -10 + doc.topMargin - 2)

    P1 = Paragraph('''N°''', ta_c)
    P2 = Paragraph('''FECHA''', ta_c)
    P3 = Paragraph('''TIPO''', ta_c)
    P4 = Paragraph('''MONTO''', ta_c)
    data = [[P1, P2, P3, P4]]
    header2 = Table(data, colWidths=[35, 85, 80, 250])
    header2.setStyle(
        TableStyle([
            ('GRID', (0, -1), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), '#50b7e6'),
            ('ALIGN', (0, 0), (-1, -3), "CENTER"),
        ]))
    w, h = header2.wrap(doc.width - 115, doc.topMargin)
    header2.drawOn(canvas, 72.5, doc.height - 40 + doc.topMargin - 93)

    # FOOTER

    footer4 = Paragraph("Fecha: " + str(fecha), ta_l7)
    w, h = footer4.wrap(doc.width - 200, doc.bottomMargin)
    footer4.drawOn(canvas, doc.height - 105, doc.topMargin + 620, h)

    canvas.restoreState()
예제 #5
0
def TranPDF(request):
    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = canvas.Canvas(buffer)
    doc = SimpleDocTemplate(
        buffer,
        pagesizes=letter,
        rightMargin=30,
        leftMargin=30,
        topMargin=176.9,
        bottomMargin=50,
        paginate_by=0,
    )
    ta_r = ParagraphStyle(
        'parrafos',
        alignment=TA_RIGHT,
        fontSize=13,
        fontName="Helvetica-Bold",
    )
    persona = []
    styles = getSampleStyleSheet()
    # TABLA NUMERO 1
    count = 0
    meses = [
        "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
        "Agosto", "Septimbre", "Octubre", "Noviembre", "Diciembre"
    ]
    data = []
    if "year" in request.GET and "mes" in request.GET:
        mes = request.GET['mes']
        year = request.GET['year']

    else:
        mes = datetime.now().month
        print(mes)
        year = datetime.now().year
    ingreso = Ingreso.objects.filter(fecha__month=mes,
                                     fecha__year=year).values_list(
                                         "fecha_t", "monto", "disponible",
                                         "tipo", "id")
    ingreso1 = Ingreso.objects.filter(fecha__month=mes,
                                      fecha__year=year).aggregate(Sum('monto'))
    egreso = Egreso.objects.filter(fecha__month=mes,
                                   fecha__year=year).values_list(
                                       "fecha_t", "monto", "disponible",
                                       "tipo", "id")
    global total, mes1
    mes1 = meses[int(mes) - 1]

    total = ingreso1['monto__sum']
    transaccion = ingreso.union(egreso).order_by('-fecha_t', '-id')
    tran = []
    if transaccion:
        for i in transaccion:
            if i[3] == True:
                tipo = 'Ingreso'
                monto = "{:,}".format(int(i[1])).replace(',', '.')
            else:
                tipo = 'Egreso'
                monto = "-{:,}".format(int(i[1])).replace(',', '.')
            count = count + 1
            data.append([count, i[0].date(), tipo, monto])
    else:
        return redirect('diezmo:transacciones')
    x = Table(data, colWidths=[35, 85, 80, 250])
    x.setStyle(
        TableStyle([
            ('GRID', (0, 0), (8, -1), 1, colors.black),
            ('ALIGN', (0, 0), (3, -1), 'CENTER'),
            ('FONTSIZE', (0, 0), (3, -1), 8),
        ]))
    persona.append(x)

    doc.build(persona,
              onFirstPage=HeaderFooterTrans,
              onLaterPages=HeaderFooterTrans,
              canvasmaker=NumberedCanvas)
    response.write(buffer.getvalue())
    buffer.close()

    return response
예제 #6
0
    def save(self):
        # We can fit ROWS_PER_PAGE rows on one page. We might want to do something
        # cute to avoid a single row on it's own page in the future, but
        # for now, just split it evenly.
        for pagenum in range(0, (len(self.rows) - 1) // self.ROWS_PER_PAGE + 1):
            self.draw_header()
            islastpage = (pagenum == (len(self.rows) - 1) // self.ROWS_PER_PAGE)

            if len(self.rows) > self.ROWS_PER_PAGE:
                suffix = " (page %s/%s)" % (pagenum + 1, len(self.rows) // self.ROWS_PER_PAGE + 1)
            else:
                suffix = ''

            self.canvas.setFont('DejaVu Serif Bold', 12)
            self.canvas.setFillColor(colors.black)
            # Center between 2 and 19 is 10.5
            self.canvas.drawCentredString(cm(10.5), cm(19), self.title)
            self.canvas.setFont('DejaVu Serif', 9)

            if self.invoicenum:
                if self.receipt:
                    self.canvas.drawCentredString(cm(10.5), cm(18.5), "Receipt for invoice number %s%s" % (self.invoicenum, suffix))
                else:
                    self.canvas.drawCentredString(cm(10.5), cm(18.5), "Invoice number %s - %s%s" % (self.invoicenum, timezone.localtime(self.invoicedate).strftime("%B %d, %Y"), suffix))
                self.canvas.setFont('DejaVu Serif Bold', 10)
                if self.receipt:
                    self.canvas.drawString(cm(15), cm(28), "Receipt #%s" % self.invoicenum)
                else:
                    self.canvas.drawString(cm(15), cm(28), "Invoice #%s" % self.invoicenum)
                    if self.bankinfo:
                        self.canvas.setFont('DejaVu Serif Bold', 8)
                        self.canvas.drawString(cm(15), cm(27.5), "Payment ref: %s" % self.paymentref)
            else:
                self.canvas.drawCentredString(cm(10.5), cm(18.5), "Receipt - %s%s" % (timezone.localtime(self.invoicedate).strftime("%B %d, %Y"), suffix))

            if pagenum == 0:
                firstcol = "Item"
            else:
                firstcol = "Item - continued from page %s" % pagenum

            if settings.EU_VAT:
                tbldata = [[firstcol, "Quantity", "Ex VAT", "VAT", "Incl VAT"]]
            else:
                tbldata = [[firstcol, "Quantity", "Price", "Total"]]
            tblcols = len(tbldata[0])

            if settings.EU_VAT:
                tbldata.extend([(self.trimstring(title, cm(9.5), "DejaVu Serif", 8),
                                 count,
                                 "%.2f %s" % (cost, settings.CURRENCY_SYMBOL),
                                 vatrate and vatrate.shortstr or "No VAT",
                                 "%.2f %s" % ((cost * count) * (1 + (vatpercent / Decimal(100))), settings.CURRENCY_SYMBOL))
                                for title, cost, count, vatrate, vatpercent in self.rows[pagenum * self.ROWS_PER_PAGE:(pagenum + 1) * self.ROWS_PER_PAGE]])
            else:
                tbldata.extend([(self.trimstring(title, cm(9.5), "DejaVu Serif", 8),
                                 count,
                                 "%.2f %s" % (cost, settings.CURRENCY_SYMBOL),
                                 "%.2f %s" % ((cost * count), settings.CURRENCY_SYMBOL))
                                for title, cost, count, vatrate, vatpercent in self.rows[pagenum * self.ROWS_PER_PAGE:(pagenum + 1) * self.ROWS_PER_PAGE]])

            style = [
                # Set global font size
                ('FONTSIZE', (0, 0), (-1, -1), 8),
                # Right-align all columnsexcept the first one (item name)
                ('ALIGN', (1, 0), (tblcols - 1, -1), 'RIGHT'),
                # Draw header line background in light gray and line under it
                ('BACKGROUND', (0, 0), (tblcols - 1, 0), colors.lightgrey),
                ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
                # Draw an outline around the whole table
                ('OUTLINE', (0, 0), (-1, -1), 1, colors.black),
            ]

            if islastpage:
                totalexcl = sum([cost * count for title, cost, count, vatrate, vatpercent in self.rows])

                if settings.EU_VAT:
                    # When EU vat enabled, calculate total fields both with and without VAT,
                    # and special-case the reverse-VAT situation.
                    totalvat = sum([(cost * count * (vatpercent / Decimal(100))).quantize(Decimal('0.01')) for title, cost, count, vatrate, vatpercent in self.rows])
                    totalincl = sum([(cost * count * (1 + vatpercent / Decimal(100))).quantize(Decimal('0.01')) for title, cost, count, vatrate, vatpercent in self.rows])

                    if self.totalvat > 0 and totalvat != self.totalvat:
                        raise Exception("Specified total VAT {0} does not match calculated VAT {1}".format(self.totalvat, totalvat))

                    if self.reverse_vat:
                        if totalvat != 0:
                            raise Exception("Can't use reverse VAT and specified VAT at the same time!")
                        vathdr = 'Total VAT *'
                        vatstr = "0 %s *" % (settings.CURRENCY_SYMBOL, )
                    else:
                        vathdr = 'Total VAT'
                        vatstr = '%.2f %s' % (totalvat, settings.CURRENCY_SYMBOL)

                    tbldata.extend([
                        ('Total excl VAT', '', '', '', '%.2f %s' % (totalexcl, settings.CURRENCY_SYMBOL)),
                        (vathdr, '', '', '', vatstr),
                        ('Total incl VAT', '', '', '', '%.2f %s' % (totalincl, settings.CURRENCY_SYMBOL)),
                    ])

                    style.extend([
                        # For the tree "total excl", "cat", "total incl" lines, span the
                        # cells together and alight right, and draw a line above them.
                        ('SPAN', (0, -3), (3, -3)),
                        ('SPAN', (0, -2), (3, -2)),
                        ('SPAN', (0, -1), (3, -1)),
                        ('ALIGN', (0, -3), (0, -1), 'RIGHT'),
                        ('LINEABOVE', (-4, -3), (-1, -3), 2, colors.black),
                    ])
                else:
                    # No EU vat, so just a simple total
                    tbldata.extend([
                        ('Total', '', '',
                         '%.2f %s' % (totalexcl, settings.CURRENCY_SYMBOL)),
                    ])

                    # Merge the cells of the total line together, right-align them, and
                    # draw a line above them.
                    style.extend([
                        ('SPAN', (0, -1), (2, -1)),
                        ('ALIGN', (0, -1), (0, -1), 'RIGHT'),
                        ('LINEABOVE', (-3, -1), (-1, -1), 2, colors.black),
                    ])

            else:
                tbldata.append(['          Continued on page %s' % (pagenum + 2), '', '', ''])
                style.append(('ALIGN', (0, -1), (-1, -1), 'CENTER'))
                style.append(('FONT', (0, -1), (-1, -1), 'DejaVu Serif Italic'))

            t = Table(tbldata, [cm(9.5), cm(1.5), cm(2.5), cm(2), cm(2.5)])
            t.setStyle(TableStyle(style))
            w, h = t.wrapOn(self.canvas, cm(10), cm(10))
            t.drawOn(self.canvas, cm(2), cm(18) - h)

            self.canvas.setFont('DejaVu Serif Bold', 10)
            if self.receipt:
                self.canvas.drawCentredString(cm(10.5), cm(17.3) - h, "This invoice was paid %s" % timezone.localtime(self.duedate).strftime("%B %d, %Y"))
            else:
                self.canvas.drawCentredString(cm(10.5), cm(17.3) - h, "This invoice is due: %s" % timezone.localtime(self.duedate).strftime("%B %d, %Y"))
                if self.bankinfo:
                    self.canvas.setFont('DejaVu Serif', 8)
                    self.canvas.drawCentredString(cm(10.5), cm(16.8) - h, "If paying with bank transfer, use payment reference %s" % self.paymentref)

            if islastpage:
                self.draw_footer()

            # Finish this page off, and optionally loop to another one
            self.canvas.showPage()

        # Last page is finished, flush the PDF output
        self.canvas.save()

        return self.pdfdata
def make_doc():
    pdf = io.BytesIO()

    doc = SimpleDocTemplate(pdf, pagesize=letter)
    styles = getSampleStyleSheet()
    styleH = styles['Heading1']

    story = []
    story.append(Paragraph('Election Details', styleH))
    data = []
    li = ['Elements', 'Description']
    data.append(li)
    li = ['Name of the Election', context1['Election']]
    data.append(li)
    li = ['Number of Voters in Election', context1['len1']]
    data.append(li)
    li = ['Number of Candidates in Election', context1['len2']]
    data.append(li)
    li = ['Number of P.Os in Election', context1['len3']]
    data.append(li)
    li = ['Election Start Date', context1['start_date']]
    data.append(li)
    li = ['Election End Date', context1['end_date']]
    data.append(li)
    li = ['Viewing Under', context1['obj'].user]
    data.append(li)
    li = ['Total votes expected ', context1['total_votes']]
    data.append(li)
    li = ['Votes counted', context1['counted_votes']]
    data.append(li)
    li = ['% voting done', context1['percentage']]
    data.append(li)
    li = ['Winner of the election', context1['winner_name']]
    data.append(li)
    li = ['Winner Votes counted', context1['winner_votes']]
    data.append(li)

    t1 = Table(data, hAlign='LEFT')

    t1.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('ALIGN', (0, 0), (0, -1), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    story.append(t1)
    story.append(Paragraph('Candidates Details', styleH))
    data = []
    li = ['Candidate Name', 'Votes Obtained']
    data.append(li)
    for i in context1['candidate_objects']:
        li = []
        li.append(i.user)
        li.append(i.votes)
        data.append(li)
    li = []
    li.append('NOTA')
    li.append(context1['nota'])
    data.append(li)
    t2 = Table(data, hAlign='LEFT')

    t2.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('ALIGN', (0, 0), (0, -1), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    story.append(t2)
    doc.build(story)
    pdf.seek(0)

    return pdf
예제 #8
0
data1 = fetch_data(data_dir, 'table_1_data.txt')
table_1 = Table(data1, (
    2 * inch,
    .91 * inch,
    .91 * inch,
    .91 * inch,
    .91 * inch,
    .91 * inch,
    .91 * inch,
))
table_1.setStyle(
    TableStyle([('BACKGROUND', (0, 0), (6, 0), DARK_GREEN),
                ('FONT', (0, 0), (6, 0), 'Helvetica-Bold'),
                ('TEXTCOLOR', (0, 0), (6, 0), colors.white),
                ('ALIGN', (0, 0), (6, 0), 'CENTER'),
                ('ALIGN', (1, 1), (-1, -1), 'CENTER'),
                ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                ('BOX', (0, 0), (-1, -1), 1, colors.black)]))

data2 = fetch_data(data_dir, "table_2_data.txt")
table_2 = Table(data2, (3.5 * inch, 1 * inch, 1 * inch, 1 * inch, 1 * inch),
                repeatRows=1)
table_2.setStyle(
    TableStyle([('BACKGROUND', (0, 0), (4, 0), DARK_GREEN),
                ('VALIGN', (0, 0), (0, 0), 'MIDDLE'),
                ('ALIGN', (0, 0), (4, 0), 'CENTER'),
                ('ALIGN', (1, 1), (-1, -1), 'CENTER'),
                ('FONT', (0, 0), (4, 0), 'Helvetica-Bold'),
                ('TEXTCOLOR', (0, 0), (4, 0), colors.white),
                ('FONT', (0, 1), (0, 1), 'Helvetica-Bold'),
예제 #9
0
__version__ = "$Id$"

# reportlab imports
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph, PageBreak, KeepTogether, CondPageBreak,FrameBreak
from reportlab.platypus.tables import TableStyle, Table

# ict-ok.org imports
from org.ict_ok.admin_utils.reports.rpt_base import RptSuperclass

rpt_tbl_style = TableStyle([\
    ('LEFTPADDING', (0,0), (-1,-1), 0),
    ('RIGHTPADDING', (0,0), (-1,-1), 0),
    #('BOTTOMPADDING', (0,0), (-1,-1), 0),
    #('TOPPADDING', (0,0), (-1,-1), 0),
    ('ALIGN', (0,0), (0,-1), 'RIGHT'),
])        

class RptTitle(RptSuperclass, Paragraph):
    """Title class for IKOMtrol reporting
    """

    def __init__(self, text, intype='Heading1', doc=None, context=None):
        """
        constructor of the object
        """
        RptSuperclass.__init__(self, doc, context)
        self.setText(text)
        self._element_type = "title"
예제 #10
0
def makePage(npm, prodi, noSurat):
    checkDir(f"./skmk/skmk-{prodi}/")

    fileName = f"./skmk/skmk-{prodi}/{npm}.pdf"

    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day = datetime.datetime.now().day
    tahunID = kelas.getTahunID()
    semester, tahun = getTahunAjaran(tahunID)
    mhs = getMahasiswa(npm)

    doc = SimpleDocTemplate(fileName,
                            pagesize=A4,
                            rightMargin=2.5 * cm,
                            leftMargin=2.5 * cm,
                            topMargin=4 * cm,
                            bottomMargin=3 * cm)
    contain = []
    styles = getSampleStyleSheet()
    styles.add(
        ParagraphStyle(name='Justify',
                       alignment=TA_JUSTIFY,
                       fontName='Times',
                       fontSize=12,
                       leading=14))
    styles.add(
        ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='Times'))

    ptext = '<font size="15"><b>SURAT KETERANGAN MASIH KULIAH</b></font>'
    contain.append(Paragraph(ptext, styles["Center"]))
    contain.append(Spacer(1, .4 * cm))

    ptext = f'<font size="12">No : {noSurat}/SKMK/BAAK/{convertRomawi(month)}/{year}</font>'
    contain.append(Paragraph(ptext, styles["Center"]))
    contain.append(Spacer(1, 1.8 * cm))

    ptext = '<font size="12">Direktur Politeknik Pos Indonesia menerangkan dengan sesungguhnya bahwa,</font>'
    contain.append(Paragraph(ptext, styles["Justify"]))
    contain.append(Spacer(1, 1 * cm))

    styleWrap = styles["BodyText"]
    styleWrap.alignment = TA_JUSTIFY
    styleWrap.fontName = 'Times'
    styleWrap.fontSize = 12
    styleWrap.leading = 14

    data = [
        ['Nama Mahasiswa', ':', mhs[0]],
        ['Tempat / Tanggal Lahir', ':', f"{mhs[1]}, {convertYmd(mhs[2])}"],
        ['Agama', ':', mhs[3]],
        [
            'Alamat Mahasiswa', ':',
            Paragraph(
                f'{mhs[4]}, Rt. {mhs[5] if mhs[5] != "NULL" else "-"}, Rw. {mhs[6] if mhs[6] != "NULL" else "-"}, {mhs[7]}, {mhs[8]} - {mhs[9]}',
                styleWrap)
        ],
        ['Program Studi', ':', mhs[10]],
        ['NPM', ':', npm],
        ['Nama Orang Tua', ':', mhs[11]],
        ['Pekerjaan Orang Tua', ':', mhs[12].strip()],
        [
            'Alamat Orang Tua', ':',
            Paragraph(
                f'{mhs[13]}, Rt. {mhs[14] if mhs[14] != "NULL" else "-"}, Rw. {mhs[15] if mhs[15] != "NULL" else "-"}',
                styleWrap)
        ],
        ['Kota, Kode Pos', ':', f'{mhs[16]}, {mhs[18]}'],
    ]
    table = Table(data, [5 * cm, .5 * cm, 10.5 * cm], [
        .6 * cm, .6 * cm, .6 * cm, 1.1 * cm, .6 * cm, .6 * cm, .6 * cm,
        .6 * cm, 1.1 * cm, .6 * cm
    ])
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Times-Roman', 12),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
    contain.append(table)
    contain.append(Spacer(1, .7 * cm))

    ptext = f'<font size="12">Adalah benar terdaftar dan aktif sebagai Mahasiswa Politeknik Pos Indonesia Semester {semester} Tahun Akademik {tahun}</font>'
    contain.append(Paragraph(ptext, styles["Justify"]))
    contain.append(Spacer(1, .8 * cm))

    ptext = '<font size="12">Demikian surat keterangan ini dibuat untuk dipergunakan seperlunya.</font>'
    contain.append(Paragraph(ptext, styles["Justify"]))
    contain.append(Spacer(1, 1 * cm))

    nik, nama = getKaBaak()

    link = makeLinkVerifiy(getKodeDosen(nik), npm)
    pathTTDKaBaak = makeQrcodeLinkVerifySign(link, npm, prodi)

    data = [
        ['', f'Bandung, {day} {convertMonth(month)} {year}'],
        ['', 'Direktur.'],
        ['', 'Ka. BAAK'],
        ['', Image(pathTTDKaBaak, 3.8 * cm, 3.8 * cm)],
        ['', nama],
    ]

    table = Table(data, [8 * cm, 8 * cm],
                  [.6 * cm, .6 * cm, .6 * cm, 4 * cm, .6 * cm])
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Times-Roman', 12),
            # ('INNERGRID', (0,0), (-1,-1), 1, colors.black),
            # ('BOX', (0,0), (-1,-1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ]))
    contain.append(table)

    doc.build(contain, onFirstPage=headerFooter, onLaterPages=headerFooter)

    sendEmail(mhs[19], f"{npm}.pdf", f"./skmk/skmk-{prodi}/", mhs[0])
예제 #11
0
def _build_invoices(prestations, invoice_number, invoice_date,
                    prescription_date, accident_id, accident_date):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    #import pydevd; pydevd.settrace()
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patientFirstName = ''
    patientAddress = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net',
                 'Heure', 'P. Pers', 'Executant'))
    for presta in prestations:
        i += 1
        patientSocNumber = presta.patient.code_sn
        patientNameAndFirstName = presta.patient
        patientName = presta.patient.name
        patientFirstName = presta.patient.first_name
        patientAddress = presta.patient.address
        patientZipCode = presta.patient.zipcode
        patientCity = presta.patient.city
        data.append(
            (i, presta.carecode.code, (presta.date).strftime('%d/%m/%Y'), '1',
             presta.carecode.gross_amount, presta.net_amount,
             (presta.date).strftime('%H:%M'), "", "300744-44"))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if (y % 10 == 0 and y != 0):
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            newData.append(
                ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', ''))
    _total_facture = _compute_sum(data[1:], 5)
    newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4),
                    _compute_sum(data[1:], 5), '', '', ''))

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' +
            'Regine SIMBA\n' + '1A, rue fort wallis\n' +
            'L-2714 Luxembourg\n' + 'T' + u"é".encode("utf-8") +
            "l: 691.30.85.84",
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44'
        ],
        [
            u'Matricule patient: %s' % smart_unicode(patientSocNumber.strip())
            + "\n" + u'Nom et Pr' + smart_unicode("e") +
            u'nom du patient: %s' % smart_unicode(patientNameAndFirstName),
            u'Nom: %s' % smart_unicode(patientName.strip()) + '\n' + u'Pr' +
            smart_unicode(u"é") +
            u'nom: %s' % smart_unicode(patientFirstName.strip()) + '\n' +
            u'Rue: %s' % patientAddress.strip() + '\n' +
            u'Code postal: %s' % smart_unicode(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_unicode(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 7),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    if (prescription_date is not None):
        elements.append(
            Paragraph(
                "Memoire d'Honoraires Num. %s en date du : %s Ordonnance du %s "
                % (invoice_number, invoice_date, prescription_date),
                styles['Heading4']))
    else:
        elements.append(
            Paragraph(
                "Memoire d'Honoraires Num. %s en date du : %s " %
                (invoice_number, invoice_date), styles['Heading4']))
    elements.append(Spacer(1, 18))

    elements.append(table)

    _2derniers_cases = Table([["", "Paiement Direct"]], [1 * cm, 4 * cm],
                             1 * [0.5 * cm],
                             hAlign='LEFT')
    _2derniers_cases.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (0, 0), 0.75, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    elements.append(Spacer(1, 18))

    elements.append(_2derniers_cases)
    _2derniers_cases = Table([["", "Tiers payant"]], [1 * cm, 4 * cm],
                             1 * [0.5 * cm],
                             hAlign='LEFT')
    _2derniers_cases.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (0, 0), 0.75, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))
    elements.append(Spacer(1, 18))
    elements.append(_2derniers_cases)
    elements.append(Spacer(1, 18))
    _total_a_payer = Table(
        [["Total " + u"à" + " payer:",
          "%10.2f Euros" % _total_facture]], [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(Spacer(1, 18))
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    _pouracquit_signature = Table(
        [["Pour acquit, le:", "Signature et cachet"]], [10 * cm, 10 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')

    _infos_iban = Table([["LU55 0019 4555 2516 1000 BCEELULL"]], [10 * cm],
                        1 * [0.5 * cm],
                        hAlign='LEFT')
    elements.append(Spacer(1, 10))
    elements.append(_infos_iban)
    if prescription_date is not None:
        _infos_iban = Table([[
            "Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" +
            "rence: %s Ordonnance du %s " % (invoice_number, prescription_date)
        ]], [10 * cm],
                            1 * [0.5 * cm],
                            hAlign='LEFT')
    else:
        _infos_iban = Table([[
            "Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" +
            "rence: %s " % invoice_number
        ]], [10 * cm],
                            1 * [0.5 * cm],
                            hAlign='LEFT')
    elements.append(_infos_iban)
    elements.append(_pouracquit_signature)
    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patientFirstName,
        "invoice_amount": newData[23][5]
    }
예제 #12
0
    def build_pdf(self, response):

        cleaned_data = self.filterset.form.cleaned_data

        agrupamento = cleaned_data['agrupamento']

        elements = []

        #print('data ini', datetime.now())
        data = self.get_data()
        #print('data fim', datetime.now())

        style = TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('LEADING', (0, 0), (-1, -1), 7),
            ('GRID', (0, 0), (-1, -1), 0.1, colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black),
            ('TOPPADDING', (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            ('LEFTPADDING', (0, 0), (-1, -1), 3),
            ('RIGHTPADDING', (0, 0), (-1, -1), 3),
        ])
        style.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE')

        #print('enumerate ini', datetime.now())
        for i, value in enumerate(data):
            if len(value) <= 1:
                style.add('SPAN', (0, i), (-1, i))

            if len(value) == 0:
                style.add('INNERGRID', (0, i), (-1, i), 0, colors.black),
                style.add('GRID', (0, i), (-1, i), -1, colors.white)
                style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black)

            if len(value) == 1:
                style.add('LINEABOVE', (0, i), (-1, i), 0.1, colors.black)

        #print('enumerate fim', datetime.now())
        # if not agrupamento or agrupamento == 'sem_agrupamento':
        #    style.add('ALIGN', (0, 0), (0, -1), 'CENTER')

        #print('table ini', datetime.now())
        rowHeights = 20
        t = LongTable(data, rowHeights=rowHeights, splitByRow=True)
        t.setStyle(style)
        if len(t._argW) == 5:
            t._argW[0] = 1.8 * cm
            t._argW[1] = 6 * cm
            t._argW[2] = 6.5 * cm
            t._argW[3] = 9.5 * cm
            t._argW[4] = 2.4 * cm
        elif len(t._argW) == 4:
            t._argW[0] = 2 * cm
            t._argW[1] = 10 * cm
            t._argW[2] = 11.5 * cm
            t._argW[3] = 3 * cm

        for i, value in enumerate(data):
            if len(value) == 0:
                t._argH[i] = 7
                continue
            for cell in value:
                if isinstance(cell, list):
                    t._argH[i] = (rowHeights) * (len(cell) -
                                                 (0 if len(cell) > 1 else 0))
                    break

        elements.append(t)
        #print('table fim', datetime.now())

        #print('build ini', datetime.now())
        doc = SimpleDocTemplate(response,
                                pagesize=landscape(A4),
                                rightMargin=1.25 * cm,
                                leftMargin=1.25 * cm,
                                topMargin=1.1 * cm,
                                bottomMargin=0.8 * cm)
        doc.build(elements)
예제 #13
0
def makePages(contain, logo, styles, tahunAjaran, noSurat, namaMhs, npmMhs, prodi, tanggal, penUtama, penPendamping, kaProdi, koor, kategori, listTTD, waktu, judul, listRevisiPenUt, listRevisiPenPen, styleWrap):
    data = [[Image(logo, 2.78 * cm, 2.38 * cm), Paragraph(f'<font size="14"><b>BERITA ACARA REVISI<br/>{kategori.upper()}<br/>POLITEKNIK POS INDONESIA<br/>TAHUN AJARAN {tahunAjaran}</b></font>', styles["CenterSpacing"]), Paragraph(f'<font size="23"><b>F10</b></font><br/><font size="11"><b>{noSurat}</b></font>', styles["CenterSpacing"])]
        ]
    table = Table(data, [3*cm, 9*cm, 6*cm], len(data)*[3*cm])
    table.setStyle(TableStyle([
        ('FONT',(0,0),(-1,-1),'Times-Roman'),
        ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
        ('BOX', (0,0), (-1,-1), 1, colors.black),
    ]))
    contain.append(table)
    contain.append(Spacer(1, .7*cm))
    
    text = f'<font size="12">Saya mahasiswa yang bertanda tangan sebagai berikut,</font>'
    contain.append(Paragraph(text, styles["Justify"]))
    contain.append(Spacer(1, .5*cm))
        
    data = [['Nama Mahasiswa', ':', namaMhs],
            ['NPM', ':', npmMhs],
            ['Judul', ':', Paragraph(judul, styleWrap)],
            ['Tanggal', ':', tanggal],
            ['Waktu', ':', waktu],
        ]
    table = Table(data, [5*cm, .5*cm, 12.5*cm], [.6*cm, .6*cm, 2.4*cm, .6*cm, .6*cm, ])
    table.setStyle(TableStyle([
        ('FONT',(0,0),(-1,-1),'Times-Roman', 12),
        ('VALIGN',(0,0),(-1,-1),'TOP'),
    ]))
    contain.append(table)
    contain.append(Spacer(1, .7*cm))
    
    text = f'<font size="12">telah melakukan revisi {kategori.title()} pada Prodi {prodi} Politeknik Pos Indonesia Tahun Ajaran {tahunAjaran} sesuai dengan peraturan yang berlaku, berdasarkan dengan perubahan aturan yang ditetapkan selama masa pandemi Covid 19 dengan kegiatan yang dilaksanakan secara daring dan dokumen elektronik.</font>'
    contain.append(Paragraph(text, styles["Justify"]))
    contain.append(Spacer(1, .5*cm))
    
    text = f'<font size="12">Berikut hasil revisi  {kategori.title()}:</font>'
    contain.append(Paragraph(text, styles["Justify"]))
    contain.append(Spacer(1, .5*cm))
    
    text = f'<font size="12">Penguji Utama</font>'
    contain.append(Paragraph(text, styles["Justify"]))
    contain.append(Spacer(1, .3*cm))
        
    data = [['No', 'Uraian', 'Tanda Tangan Mhs']
        ]
    data.extend(listRevisiPenUt)
    
    table = Table(data, [1.5*cm, 10*cm, 4*cm], len(data)*[1.5*cm])
    table.setStyle(TableStyle([
        ('FONT',(0,0),(-1,-1),'Times-Roman', 12),
        ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
        ('ALIGN', (0,0), (2,0), 'CENTER'),
        ('ALIGN', (0,0), (0,-1), 'CENTER'),
        ('SPAN', (2, 1), (-1, -1)),
        ('INNERGRID', (0,0), (-1,-1), 1, colors.black),
        ('BOX', (0,0), (-1,-1), 1, colors.black),
    ]))
    contain.append(table)
    contain.append(Spacer(1, .7*cm))
    
    text = f'<font size="12">Penguji Pendamping</font>'
    contain.append(Paragraph(text, styles["Justify"]))
    contain.append(Spacer(1, .3*cm))
    
    data = [['No', 'Uraian', 'Tanda Tangan Mhs']
        ]
    
    data.extend(listRevisiPenPen)
    table = Table(data, [1.5*cm, 10*cm, 4*cm], len(data)*[1.4*cm])
    table.setStyle(TableStyle([
        ('FONT',(0,0),(-1,-1),'Times-Roman', 12),
        ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
        ('ALIGN', (0,0), (2,0), 'CENTER'),
        ('ALIGN', (0,0), (0,-1), 'CENTER'),
        ('SPAN', (2, 1), (-1, -1)),
        ('INNERGRID', (0,0), (-1,-1), 1, colors.black),
        ('BOX', (0,0), (-1,-1), 1, colors.black),
    ]))
    contain.append(table)
    contain.append(Spacer(1, .7*cm))
    
    path = './revisisidang/qrcodeberitaacara/'
    
    data = [[f'Bandung, {tanggal}'],
            ['Mengetahui:'],
            ['Penguji Utama', '', 'Penguji Pendamping'],
            [Image(f'{path}{listTTD[0]}.png', 4 * cm, 4 * cm), '', Image(f'{path}{listTTD[1]}.png', 4 * cm, 4 * cm)],
            [penUtama, '', penPendamping],
            ['Diperiksa oleh,'],
            [Paragraph(f'<font size="12">Ketua<br/>Program Studi {prodi}</font>', styles["CenterSpacing"]), '', Paragraph(f'<font size="12">Koordinator {kategori.title()}<br/>Program Studi {prodi}</font>', styles["CenterSpacing"])],
            [Image(f'{path}{listTTD[3]}.png', 4 * cm, 4 * cm), '', Image(f'{path}{listTTD[2]}.png', 4 * cm, 4 * cm)],
            [kaProdi, '', koor],
        ]
    table = Table(data, [8.5*cm, 1*cm, 8.5*cm], [.8*cm, .8*cm,.8*cm,4.5*cm,.8*cm,.8*cm,1.8*cm,4.5*cm,.8*cm])
    table.setStyle(TableStyle([
        ('FONT',(0,0),(-1,-1),'Times-Roman', 12),
        ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
        ('ALIGN', (0,0), (-1,-1), 'CENTER'),
        ('SPAN', (0, 0), (2, 0)),
        ('SPAN', (0, 1), (2, 1)),
        ('SPAN', (0, 5), (2,5))
        
    ]))
    contain.append(table)
    contain.append(Spacer(1, .7*cm))
def _build_invoices(prestations, invoice_number, invoice_date,
                    prescription_date, accident_id, accident_date,
                    patient_invoice_date, patient):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patient_first_name = ''
    patient_address = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'CNS',
                 'Part. Client'))
    for presta in prestations:
        i += 1
        patientSocNumber = patient.code_sn
        patientNameAndFirstName = patient
        patientName = patient.name
        patient_first_name = patient.first_name
        patient_address = patient.address
        patientZipCode = patient.zipcode
        patientCity = patient.city
        data.append((
            i, presta.carecode.code, (presta.date).strftime('%d/%m/%Y'), '1',
            presta.carecode.gross_amount(presta.date),
            presta.carecode.net_amount(
                presta.date, patient.is_private,
                patient.participation_statutaire
                and patient.age > 18), "%10.2f" %
            (decimal.Decimal(presta.carecode.gross_amount(presta.date)) -
             decimal.Decimal(
                 presta.carecode.net_amount(presta.date, patient.is_private,
                                            patient.participation_statutaire)))
        ))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if (y % 10 == 0 and y != 0):
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            _part_sum = _compute_sum(data[y - 9:y + 1], 6)
            newData.append(('', '', '', 'Sous-Total', "%10.2f" % _gross_sum,
                            "%10.2f" % _net_sum, "%10.2f" % _part_sum))
    _total_facture = _compute_sum(data[1:], 5)
    _participation_personnelle = decimal.Decimal(_compute_sum(
        data[1:], 4)) - decimal.Decimal(_total_facture)
    newData.append(('', '', '', 'Total', "%10.2f" % _compute_sum(data[1:], 4),
                    "%10.2f" % _compute_sum(data[1:], 5),
                    "%10.2f" % _compute_sum(data[1:], 6)))

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' +
            'Regine SIMBA\n' + '1A, rue fort wallis\n' +
            'L-2714 Luxembourg\n' + u"Tél: 691.30.85.84",
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44'
        ],
        [
            u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) +
            "\n" + u'Nom et Pr' + smart_text("e") +
            u'nom du patient: %s' % smart_text(patientNameAndFirstName),
            u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' +
            smart_text(u"é") +
            u'nom: %s' % smart_text(patient_first_name.strip()) + '\n' +
            u'Rue: %s' % patient_address.strip() + '\n' +
            u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_text(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2.5 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    if (prescription_date is not None):
        elements.append(
            Paragraph(
                u"Mémoire d'Honoraires Num. %s en date du : %s Ordonnance du %s "
                % (invoice_number, invoice_date, prescription_date),
                styles['Heading4']))
    else:
        elements.append(
            Paragraph(
                u"Mémoire d'Honoraires Num. %s en date du : %s " %
                (invoice_number, invoice_date), styles['Heading4']))

    elements.append(Spacer(1, 18))

    elements.append(table)

    elements.append(Spacer(1, 18))

    _total_a_payer = Table([[
        "Total participation personnelle:",
        "%10.2f Euros" % _participation_personnelle
    ]], [10 * cm, 5 * cm],
                           1 * [0.5 * cm],
                           hAlign='LEFT')
    elements.append(Spacer(1, 18))
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    elements.append(Spacer(1, 10))

    if patient_invoice_date is not None:
        from utils import setlocale
        with setlocale('en_GB.utf8'):
            if isinstance(patient_invoice_date, unicode):
                elements.append(
                    Table([[
                        u"Date envoi de la présente facture: %s " %
                        patient_invoice_date.strftime('%d %B %Y').encode(
                            'utf-8')
                    ]], [10 * cm],
                          1 * [0.5 * cm],
                          hAlign='LEFT'))
            else:
                elements.append(
                    Table([[
                        u"Date envoi de la présente facture: %s " %
                        patient_invoice_date.strftime('%d %B %Y').decode(
                            'utf-8')
                    ]], [10 * cm],
                          1 * [0.5 * cm],
                          hAlign='LEFT'))
        elements.append(Spacer(1, 10))

    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patient_first_name,
        "invoice_amount": newData[23][5],
        "invoice_pp": newData[23][6]
    }
예제 #15
0
def _build_final_page(total, order_number):
    elements = []
    data = [["RELEVE DES NOTES D’HONORAIRES DES"],
            ["ACTES ET SERVICES DES INFIRMIERS"]]
    table = Table(data, [10 * cm], [0.75 * cm, 0.75 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('INNERGRID', (0, 0), (-1, -1), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 12),
            ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
    elements.append(table)
    elements.append(Spacer(1, 18))
    data2 = [[
        u"Identification du fournisseur de", config.NURSE_NAME, "",
        u"réservé à l’union des caisses de maladie"
    ], [u"soins de santé", "", "", ""],
             [u"Coordonnées bancaires :", config.MAIN_BANK_ACCOUNT, "", ""],
             ["Code: ", config.MAIN_NURSE_CODE, "", ""]]
    table2 = Table(data2, [5 * cm, 3 * cm, 3 * cm, 7 * cm],
                   [1.25 * cm, 0.5 * cm, 1.25 * cm, 1.25 * cm])
    table2.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                    ('ALIGN', (3, 0), (3, 0), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 0, colors.white),
                    ('SPAN', (1, 2), (2, 2)),
                    ('FONTSIZE', (0, 0), (-1, -1), 8),
                    ('BOX', (3, 0), (3, 3), 0.25, colors.black),
                    ('BOX', (3, 0), (3, 1), 0.25, colors.black),
                    ('BOX', (1, 3), (1, 3), 1, colors.black)]))
    elements.append(table2)
    elements.append(Spacer(1, 20))
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    elements.append(
        Paragraph(
            u"Récapitulation des notes d’honoraires du chef de la fourniture de soins de santé dispensés aux personnes protégées relevant de l’assurance maladie / assurance accidents ou de l’assurance dépendance.",
            styles['Justify']))
    elements.append(Spacer(2, 20))
    elements.append(
        Paragraph(
            u"Pendant la période du :.................................. au :..................................",
            styles['Justify']))
    data3 = [[
        "Nombre des mémoires d’honoraires ou\nd’enregistrements du support informatique:",
        order_number
    ]]
    table3 = Table(data3, [9 * cm, 8 * cm], [1.25 * cm])
    table3.setStyle(
        TableStyle([('ALIGN', (0, 0), (0, 0), 'LEFT'),
                    ('ALIGN', (-1, -1), (-1, -1), 'CENTER'),
                    ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE'),
                    ('INNERGRID', (0, 0), (-1, -1), 0, colors.white),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                    ('BOX', (1, 0), (-1, -1), 1.25, colors.black)]))
    elements.append(Spacer(2, 20))
    elements.append(table3)
    elements.append(Spacer(2, 20))
    data4 = [[
        u"Montant total des honoraires à charge de\nl’organisme assureur (montant net cf. zone 14) du\nmém. d’honoraires):",
        "%.2f EUR" % round(total, 2)
    ]]
    table4 = Table(data4, [9 * cm, 8 * cm], [1.25 * cm])
    table4.setStyle(
        TableStyle([('ALIGN', (0, 0), (0, 0), 'LEFT'),
                    ('ALIGN', (-1, -1), (-1, -1), 'CENTER'),
                    ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE'),
                    ('INNERGRID', (0, 0), (-1, -1), 0, colors.white),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                    ('BOX', (1, 0), (-1, -1), 1.25, colors.black)]))
    elements.append(table4)
    elements.append(Spacer(40, 60))
    styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
    elements.append(
        Paragraph(
            u"Certifié sincère et véritable, mais non encore acquitté: ________________ ,le ______________________",
            styles['Left']))
    return elements
예제 #16
0
                           leading=15,
                           alignment=TA_CENTER)
styleSubTitleBold = ParagraphStyle('subtitle',
                                   fontName='David-Bold',
                                   fontSize=15,
                                   alignment=TA_CENTER)
styleSubTitle = ParagraphStyle('subtitle',
                               fontName='David',
                               fontSize=15,
                               alignment=TA_CENTER)

saleTableStyle = TableStyle([
    ('FONTNAME', (0, 0), (-1, 0), 'David-Bold'),
    ('FONTNAME', (0, 1), (-1, -1), 'David'),
    ('FONTSIZE', (0, 0), (-1, -1), 9),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ('LEFTPADDING', (0, 0), (-1, -1), 8),
    ('RIGHTPADDING', (0, 0), (-1, -1), 8),
])
nhsalariesTableStyle = TableStyle([
    ('FONTNAME', (0, 0), (-1, 0), 'David-Bold'),
    ('FONTNAME', (0, 1), (-1, -1), 'David'),
    ('FONTSIZE', (0, 0), (-1, -1), 9),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ('LEFTPADDING', (0, 0), (-1, -1), 8),
    ('RIGHTPADDING', (0, 0), (-1, -1), 8),
])
salariesTableStyle = TableStyle([
예제 #17
0
    para_text = six.text_type(etree.tostring(res_text))
    para_text = para_text[para_text.find('>') + 1:]
    para_text = para_text.replace('</TEXT>', '')
    para_text = para_text.replace("\\n", " ")
    para_text = para_text.replace("\\t", " ")
    para_text = para_text.replace("\\r", " ")
    para_text = para_text.replace("\\'", "&#130;")
    para_text = para_text.replace("'", "")
    para_text = para_text.replace("&#130;", "'")
    para_text = para_text.replace('"', "&#34;")
    para_text = re.sub(pattern, ' ', para_text)
    para_text = para_text.strip()
    return para_text


TABLE_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 0.3 * mm, (0, 0, 0)),
                          ('BOX', (0, 0), (-1, -1), 0.3 * mm, (0, 0, 0))])

g_initial_fonts = False


def initial_fonts():
    global g_initial_fonts
    if not g_initial_fonts:
        font_dir_path = join(dirname(__file__), 'fonts')
        pdfmetrics.registerFont(
            TTFont('sans-serif', join(font_dir_path, 'FreeSans.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-bold', join(font_dir_path, 'FreeSansBold.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-italic',
                   join(font_dir_path, 'FreeSansOblique.ttf')))
예제 #18
0
def ingresopaciente(request):
    fechahoy = datetime.now()
    ancho, alto = letter  # alto=792,ancho=612 - posicion normal
    nom_arch = "infoingreso" + nombrearch() + ".pdf"  # gestion remota
    #
    # desarrollo
    logo_corp = os.getcwd(
    ) + "\\misitio\\ai\\static\\img\\Logo_AsistenciaIntegral.jpg"
    c = canvas.Canvas(os.getcwd() + "\\pdfs\\" + nom_arch, pagesize=letter)
    #
    #produccion
    #logo_corp = os.getcwd()+"/misitio/staticfiles/img/Logo_AsistenciaIntegral.jpg"
    #c = canvas.Canvas(os.getcwd() +"/misitio/pdfs/"+ nom_arch, pagesize=letter)
    #
    c.setPageSize((ancho, alto))
    #
    rut_aux = request.session['rut_x']
    paciente = Pacientes.objects.get(rut=rut_aux)

    if paciente.fe_ini == None:
        return HttpResponse("Paciente no posee fecha de inicio")

    fe_nac = paciente.fe_nac
    edad_x = edad(paciente.fe_nac)  # en misfunciones.py
    sexo_x = "Masculino"
    if paciente.sexo == 2:
        sexo_x = "Femenino"

    domicilio_x = paciente.direccion
    fono_pcte = paciente.fono_pcte
    fe_nac = paciente.fe_nac

    region_x = "(sin definir)"
    region = Param.objects.filter(tipo='REGI', codigo=paciente.region)
    for re in region:
        region_x = re.descrip

    comuna_x = "(sin definir)"
    comuna = Param.objects.filter(tipo='COMU', codigo=paciente.comuna)
    for co in comuna:
        comuna_x = co.descrip

    # produccion
    #path_x = os.getcwd() +"/misitio/pdfs/"

    # Desarrollo
    path_x = os.getcwd() + '\\pdfs\\'

    arch_y = os.listdir(path_x)
    for arch_pdf in arch_y:
        remove(path_x + arch_pdf)
    #
    ## ####comienza primera pagina ##############################
    y = 710
    c.drawImage(logo_corp, 25, y, 190, 80)  # (IMAGEN, X,Y, ANCHO, ALTO)
    y = 700
    c.setFont('Helvetica-Bold', 11)
    c.drawString(198, y, "INFORME INGRESO PACIENTE")
    c.setFont('Helvetica', 11)
    # subrrayado de "informe ingreso paciente"
    y = y - 20
    c.line(
        197, y + 16, 361, y + 16
    )  # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final
    #
    #
    y = y - 10
    c.drawString(420, y, "Fecha:_____/_____/______")
    #
    y = y - 30

    # DEFINICION DE PRIMERA GRID ###################################
    c.setFont('Helvetica-Bold', 10)
    c.drawString(50, 620, "Datos del paciente")
    c.setFont('Helvetica', 10)
    y = y - 15

    data = [
        ["Nombre completo", paciente.nombre],
        ["RUT", paciente.rut],
        ["Fecha de nacimiento", fecha_ddmmaaaa(fe_nac)],
        ["Edad", edad(fe_nac)],
        ["Sexo", sexo_x],
        ["Dirección", paciente.direccion],
        ["Comuna", comuna_x],
        ["Región", region_x],
        ["Telofono", paciente.fono_pcte],
        ["Apoderado del paciente", paciente.n_apod],
        ["Teléfono del apoderado del paciente", paciente.f_apod],
        ["Personas que vive en el domicilio y parentesco", ""],
    ]

    # definicion de cada columna (primera grid)
    t = Table(data, colWidths=[230, 280])

    t.setStyle(
        TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("ALIGN", (-2, 1), (-2, -1), "LEFT"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    w, h = t.wrap(100, 100)  # OBLIGAORIO
    t.drawOn(c, 50, 390, 0)  # DIBUJA LA GRID EN MEMORIA
    # FIN DE DEFINICION DE PRIMERA GRID
    #
    #
    #
    # INICIA DEFINICION DE SEGUNDA GRID ################################
    y = 365
    c.setFont('Helvetica-Bold', 10)
    c.drawString(50, y, "Datos de la empresa de cuidados domiciliarios:")
    c.setFont('Helvetica', 10)
    y = y - 15
    #
    data = [
        ["Nombre empresa", ""],
        ["Nombre enfermera", ""],
        ["Telefono enfermera o coordinador de la empresa", ""],
    ]

    # Definicion de cada columna (segunda grid)
    t = Table(data, colWidths=[230, 280])

    t.setStyle(
        TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("ALIGN", (-2, 1), (-2, -1), "LEFT"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    w, h = t.wrap(100, 100)  # OBLIGAORIO
    t.drawOn(c, 50, 300, 0)  # DIBUJA LA GRID EN MEMORIA

    # INICIA DEFINICION DE TERCERA GRID ################################
    y = 275
    c.setFont('Helvetica-Bold', 10)
    c.drawString(50, y, "Datos contacto:")
    c.setFont('Helvetica', 10)
    y = y - 15
    #
    data = [
        ["Contacto", ""],
        ["Fono contacto", ""],
        ["", ""],
    ]

    # Definicion de cada columna (tercera grid)
    t = Table(data, colWidths=[230, 280])

    t.setStyle(
        TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("ALIGN", (-2, 1), (-2, -1), "LEFT"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    w, h = t.wrap(100, 100)  # OBLIGAORIO
    t.drawOn(c, 50, 210, 0)  # posiciona y DIBUJA LA GRID EN MEMORIA

    # INICIA DEFINICION DE CUARTA GRID ################################
    y = 190
    c.setFont('Helvetica-Bold', 10)
    c.drawString(50, y, "Datos de accidente:")
    c.setFont('Helvetica', 10)
    y = y - 15
    #
    data = [
        ["Contacto", ""],
        ["Fono contacto", ""],
        ["", ""],
    ]

    # Definicion de cada columna (cuarta grid)
    t = Table(data, colWidths=[230, 280])

    t.setStyle(
        TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("ALIGN", (-2, 1), (-2, -1), "LEFT"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    w, h = t.wrap(100, 100)  # OBLIGAORIO
    t.drawOn(c, 50, 125, 0)  # posiciona y DIBUJA LA GRID EN MEMORIA
    #
    ##### INICIA CAJA DE COMENTARIOS #############################
    c.setFont('Helvetica-Bold', 10)
    c.drawString(50, 105, "Comentarios de ingreso:")
    c.setFont('Helvetica', 10)

    # rectangulo
    c.rect(50, 50, 510, 47)

    ## ########  FIN DEL REPORTE ####################
    c.showPage()  #salto de pagina
    c.save()  #Archivamos y cerramos el canvas
    #Lanzamos el pdf creado
    os.system(nom_arch)

    #desarrollo
    return FileResponse(open(os.getcwd() + '\\pdfs\\' + nom_arch, 'rb'),
                        content_type='application/pdf')
예제 #19
0
    def save(self):
        self.draw_header()

        self.canvas.drawCentredString(cm(10.5), cm(19), "REFUND NOTE {0} FOR INVOICE NUMBER {1}".format(self.refundid, self.invoicenum))

        self.canvas.drawString(cm(2), cm(18), "Reason for refund: {0}".format(self.reason))

        tblpaid = [
            ["Amount paid"],
            ["Item", "Amount"],
            ["Amount", "{0:.2f} {1}".format(self.invoiceamount, settings.CURRENCY_SYMBOL)],
        ]
        tblrefunded = [
            ["Amount refunded"],
            ["Item", "Amount"],
            ["Amount", "{0:.2f} {1}".format(self.refundamount, settings.CURRENCY_SYMBOL)],
        ]
        tblprevious = [
            ["Amount previously refunded"],
            ["Item", "Amount"],
            ["Amount", "{0:.2f} {1}".format(self.previousamount, settings.CURRENCY_SYMBOL)],
        ]
        if self.invoicevat:
            tblpaid.extend([
                ["VAT", "{0:.2f} {1}".format(self.invoicevat, settings.CURRENCY_SYMBOL)],
                ["", "{0:.2f} {1}".format(self.invoiceamount + self.invoicevat, settings.CURRENCY_SYMBOL)],
            ])
            tblrefunded.extend([
                ["VAT", "{0:.2f} {1}".format(self.refundvat, settings.CURRENCY_SYMBOL)],
                ["", "{0:.2f} {1}".format(self.refundamount + self.refundvat, settings.CURRENCY_SYMBOL)],
            ])
            tblprevious .extend([
                ["VAT", "{0:.2f} {1}".format(self.previousvat, settings.CURRENCY_SYMBOL)],
                ["", "{0:.2f} {1}".format(self.previousamount + self.previousvat, settings.CURRENCY_SYMBOL)],
            ])

        style = [
            ('SPAN', (0, 0), (1, 0)),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
            ('ALIGN', (0, 0), (0, 0), 'CENTER'),
            ('ALIGN', (1, 1), (1, -1), 'RIGHT'),
            ('LINEBELOW', (0, 1), (-1, 1), 1, colors.black),
            ('OUTLINE', (0, 0), (-1, -1), 1, colors.black),
        ]
        if self.invoicevat:
            style.append(
                ('LINEABOVE', (-1, -1), (-1, -1), 2, colors.black),
            )

        t = Table(tblpaid, [cm(10.5), cm(2.5), cm(1.5), cm(2.5)])
        t.setStyle(TableStyle(style))
        w, h = t.wrapOn(self.canvas, cm(10), cm(10))
        t.drawOn(self.canvas, (self.canvas._pagesize[0] - w) // 2, cm(17) - h)

        if self.previousamount:
            t = Table(tblprevious, [cm(10.5), cm(2.5), cm(1.5), cm(2.5)])
            t.setStyle(TableStyle(style))
            w, h = t.wrapOn(self.canvas, cm(10), cm(10))
            t.drawOn(self.canvas, (self.canvas._pagesize[0] - w) // 2, cm(17) - h * 2 - cm(1))
            extraofs = h + cm(1)
        else:
            extraofs = 0

        t = Table(tblrefunded, [cm(10.5), cm(2.5), cm(1.5), cm(2.5)])
        t.setStyle(TableStyle(style))
        w, h = t.wrapOn(self.canvas, cm(10), cm(10))
        t.drawOn(self.canvas, (self.canvas._pagesize[0] - w) // 2, cm(17) - h * 2 - cm(1) - extraofs)

        self.canvas.drawCentredString(cm(10.5), cm(16.3) - h * 2 - cm(2) - extraofs, "This refund was issued {0}".format(timezone.localtime(self.refunddate).strftime("%B %d, %Y")))

        if self.paymentmethod:
            self.canvas.drawCentredString(cm(10.5), cm(16.3) - h * 2 - cm(3) - extraofs, "Refunded to the original form of payment: {0}.".format(self.paymentmethod))

        self.canvas.showPage()
        self.canvas.save()

        return self.pdfdata
예제 #20
0
def gestionremota2(request):
    fechahoy = datetime.now()
    ancho, alto = letter  # alto=792,ancho=612 - posicion normal
    nom_arch = "gestionre2" + nombrearch() + ".pdf"  # gestion remota
    #
    # desarrollo
    logo_corp = os.getcwd(
    ) + "\\misitio\\ai\\static\\img\\Logo_AsistenciaIntegral.jpg"
    c = canvas.Canvas(os.getcwd() + "\\pdfs\\" + nom_arch, pagesize=letter)
    #
    #produccion
    #logo_corp = os.getcwd()+"/misitio/staticfiles/img/Logo_AsistenciaIntegral.jpg"
    #c = canvas.Canvas(os.getcwd() +"/misitio/pdfs/"+ nom_arch, pagesize=letter)
    #
    c.setPageSize((ancho, alto))
    #
    rut_aux = request.session['rut_x']
    paciente = Pacientes.objects.get(rut=rut_aux)

    if paciente.fe_ini == None:
        return HttpResponse("Paciente no posee fecha de inicio")

    # produccion
    #path_x = os.getcwd() +"/misitio/pdfs/"

    # Desarrollo
    path_x = os.getcwd() + '\\pdfs\\'

    arch_y = os.listdir(path_x)
    for arch_pdf in arch_y:
        remove(path_x + arch_pdf)
    #
    ## ####comienza primera pagina ##############################
    y = 710
    c.drawImage(logo_corp, 10, y, 190, 80)  # (IMAGEN, X,Y, ANCHO, ALTO)
    y = 700
    c.setFont('Helvetica-Bold', 11)
    c.drawString(190, y, "GESTION REMOTA DE PACIENTES CIMAS + D")
    c.setFont('Helvetica', 11)
    #
    # subrrayado de "GESTION REMOTA DE PACIENTES"
    y = y - 20
    c.line(
        190, y + 16, 436, y + 16
    )  # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final
    #
    c.setFont('Helvetica-Bold', 10)
    y = y - 20
    c.drawString(50, y,
                 "NOMBRE: " + str(paciente.nombre) + "      R.U.T.:" + rut_aux)
    y = y - 20
    c.drawString(50, y, "FECHA: " + "_______/_________/__________")
    y = y - 30
    c.drawString(
        50, y,
        "MOTIVO POR EL QUE SE REALIZA: ________________________________")

    y = y - 30
    c.drawString(50, y, "2.-EVALUACION COGNITIVA:")
    #
    c.setFont('Helvetica', 10)
    y = y - 20
    # rectangulo
    c.rect(50, y - 7, 510, 17)
    c.drawString(53, y, "Test Memoria Acortado - SPMSQ -  E. PFEIFER 1975")
    y = y - 15
    # rectangulo
    c.rect(50, y - 9, 510, 17)
    c.drawString(53, y - 3,
                 "EVALUABLE:______________ NOEVALUABLE:_________________")
    y = y - 25
    c.drawString(
        50, y,
        "Pregunte desde el número 1 al 10, y complete las respuestas. Pregunte el número 4 A solo si el paciente no "
    )
    y = y - 15
    c.drawString(50, y, "tiene telefono. Anote al final el número de errores.")
    #
    y = y - 32
    c.drawString(
        50, y, "Se acepta UN ERROR MAS, si tiene educación basica o ninguna")
    y = y - 25
    c.drawString(50, y,
                 "Se acepta UN ERROR MENOS, si tiene educación superior")
    #
    ### COMIENZA DEFINICION GRID
    data = [
        ["Bueno", "Malo", "Pregunta"],
        ["", "", "¿Que fecha es hoy? (dia-mes-año)"],
        ["", "", "¿ Que dia de la semana es hoy ?"],
        ["", "", "¿Cual es el nombre de este lugar o edificio?"],
        [
            "", "",
            "¿Cual es su número de telefono? 4A ¿Cual es su dirección ?(solo si no tiene telefono)"
        ],
        ["", "", "¿Que edad tien usted?"],
        ["", "", "¿En que fecha nacio? (dia-mes-año)"],
        ["", "", "¿Cual es el presidente de Chile Actualmente?"],
        ["", "", "¿Cual fue el presidente anterior?"],
        ["", "", "¿Cual es el appellido de su madre?"],
        [
            "", "",
            "A 20, restale 3, y continue restandole 3 a cada resultado hasta el final (20-17-14-11-8-5-2)"
        ],
    ]

    # definicion de cada columna (primera grid)
    t = Table(data, colWidths=[43, 43, 420])

    t.setStyle(
        TableStyle([
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
            ("ALIGN", (-2, 1), (-2, -1), "LEFT"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    w, h = t.wrap(100, 100)  # OBLIGAORIO
    t.drawOn(c, 50, 220, 0)  # DIBUJA LA GRID EN MEMORIA
    # FIN DE DEFINICION DE LA GRID

    # rectangulo
    y = 130
    c.roundRect(50, y, 506, 91, 4, stroke=1, fill=0)

    c.drawString(53, y + 68, "Total")
    c.drawString(142, y + 68, "0-2 errores: Funciones intelectuales intactas")
    y = 178
    c.drawString(142, y, "3-4 errores: Deterioro intelectual leve")
    y = y - 20
    c.drawString(142, y, "5-7 errores: Deterioro intelectual moderado")
    y = y - 20
    c.drawString(142, y, "8-10 errores: Deterioro intelectual severo")
    #
    c.setFont('Helvetica-Bold', 10)
    y = y - 30
    c.drawString(50, y, "Observaciones:")
    c.setFont('Helvetica', 10)
    y = y - 30
    c.line(
        50, y + 16, 556, y + 16
    )  # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final
    y = y - 30
    c.line(
        50, y + 16, 556, y + 16
    )  # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final
    y = y - 30
    c.line(
        50, y + 16, 556, y + 16
    )  # x,y,z,w en donde x=posic. horiz. inicial,y=poc.inicial verical,w=poc.vert.final

    ## ########  FIN DEL REPORTE ####################
    c.showPage()  #salto de pagina
    c.save()  #Archivamos y cerramos el canvas
    #Lanzamos el pdf creado
    os.system(nom_arch)

    #desarrollo
    return FileResponse(open(os.getcwd() + '\\pdfs\\' + nom_arch, 'rb'),
                        content_type='application/pdf')
예제 #21
0
def IngresoPDF(request):
    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = canvas.Canvas(buffer)
    doc = SimpleDocTemplate(
        buffer,
        pagesizes=letter,
        rightMargin=30,
        leftMargin=30,
        topMargin=176.9,
        bottomMargin=50,
        paginate_by=0,
    )
    ta_r = ParagraphStyle(
        'parrafos',
        alignment=TA_RIGHT,
        fontSize=13,
        fontName="Helvetica-Bold",
    )
    persona = []
    styles = getSampleStyleSheet()
    # TABLA NUMERO 1
    count = 0
    data = []
    filtro = Ingreso.objects.all().order_by('-fecha', '-id')
    if (request.GET['tipo']):
        tipo = request.GET['tipo']
        c = filtro.filter(tipo_de_pago=tipo)

    else:
        c = filtro
    if c:
        for i in c:
            count = count + 1
            if int(i.tipo_de_pago_id) == 2:
                numero = 'No aplica'
            else:
                numero = i.numero_trans
            data.append([
                count, i.fecha,
                str(i.monto) + ' bs.', numero,
                str(i.tipo_de_pago.tipopago), i.persona.nombre
            ])
    else:
        return redirect('diezmo:ingresos')
    x = Table(data, colWidths=[35, 85, 80, 80, 150, 80])
    x.setStyle(
        TableStyle([
            ('GRID', (0, 0), (12, -1), 1, colors.black),
            ('ALIGN', (0, 0), (3, -1), 'CENTER'),
            ('FONTSIZE', (0, 0), (4, -1), 8),
        ]))
    persona.append(x)

    doc.build(persona,
              onFirstPage=HeaderFooterIngreso,
              onLaterPages=HeaderFooterIngreso,
              canvasmaker=NumberedCanvas)
    response.write(buffer.getvalue())
    buffer.close()

    return response
예제 #22
0
class PDFTable(TableBase):
    """Table generator that yields a PDF representation of the data"""

    rowoddcolor = colors.Color(.92, .92, .92)
    gridcolor = colors.Color(.8, .8, .8)
    rowevencolor = colors.Color(.98, .98, .98)
    headerbackgroundcolor = colors.Color(.004, 0, .5)

    # Every table starts off with this style
    tablebasestyle = TableStyle([
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('INNERGRID', (0, 0), (-1, -1), 1, gridcolor),
    ])

    # The parent table is the outside wrapper around everything
    tableparentstyle = TableStyle([
        ('ROWBACKGROUNDS', (0, 0), (-1, -1), [rowoddcolor, rowevencolor]),
        ('LINEABOVE', (0, 1), (-1, -2), 1, colors.black),
        ('LINEBELOW', (0, 1), (-1, -2), 1, colors.black),
        ('BOX', (0, 0), (-1, -1), 1, colors.black),
    ])

    # Give content rows a little bit of side padding
    tablerowstyle = TableStyle([
        ('LEFTPADDING', (0, 0), (-1, -1), 3),
        ('RIGHTPADDING', (0, 0), (-1, -1), 3),
    ])

    tableheaderstyle = TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), headerbackgroundcolor),
    ])

    titlestyle = ParagraphStyle(name='Title Style',
                                fontName='Helvetica-Bold',
                                fontSize=16)
    explanationstyle = ParagraphStyle(name='Explanation Style',
                                      fontName='Helvetica',
                                      fontSize=12)
    headercellstyle = ParagraphStyle(name='Table Header Style',
                                     fontName='Helvetica-Bold',
                                     textColor=colors.white)
    contentcellstyle = ParagraphStyle(name='Table Cell Style',
                                      fontName='Helvetica',
                                      fontSize=8)
    contentmoneycellstyle = ParagraphStyle(name='Table Cell Style',
                                           fontName='Helvetica',
                                           fontSize=8,
                                           alignment=TA_RIGHT)

    def _rendercell(self, cell):
        """Render data as a Paragraph"""

        value = self._cast(cell)

        # Wrap the cell's contents in onion-tag goodness
        if cell.style.bold:
            value = '<b>%s</b>' % value

        if cell.style.money:
            style = self.contentmoneycellstyle
        else:
            style = self.contentcellstyle
        return Paragraph(value, style)

    def render(self, rowsets):
        """Return the data as a binary string holding a PDF"""

        # Start by creating the table headers
        rowtables = []
        if self.headers:
            for headerrow in self.headers:
                widths = [
                    headercolumn.style.width for headercolumn in headerrow
                ]
                # Let ReportLab calculate the width of the last column
                # so that it occupies the total remaining open space
                widths[-1] = None
                headertable = Table([[
                    Paragraph(headercolumn.title, self.headercellstyle)
                    for headercolumn in headerrow
                ]],
                                    style=self.tablebasestyle,
                                    colWidths=widths)
                headertable.setStyle(self.tablerowstyle)
                headertable.setStyle(self.tableheaderstyle)
                rowtables.append([headertable])

        # Then create a table to hold the contents of each line
        for rowset in rowsets:
            subrowtables = []
            if isinstance(rowset, TableRow):
                rowset = [rowset]
            for subrow in rowset:
                subrowtable = Table(
                    [[self._rendercell(cell) for cell in subrow]],
                    style=self.tablebasestyle,
                    colWidths=[cell.style.width for cell in subrow])
                subrowtable.setStyle(self.tablerowstyle)
                subrowtables.append([subrowtable])

            rowtable = Table(subrowtables, style=self.tablebasestyle)
            rowtables.append([rowtable])

        # Wrap all of those rows into an outer table
        parenttable = Table(rowtables, style=self.tablebasestyle, repeatRows=1)
        parenttable.setStyle(self.tableparentstyle)

        # Finally, build the list of elements that the table will
        # comprise
        components = []
        if self.title:
            components.append(Paragraph(self.title, self.titlestyle))
        if self.explanation:
            components.extend([
                Spacer(1, .2 * inch),
                Paragraph(self.explanation, self.explanationstyle)
            ])
        components.extend([Spacer(1, .3 * inch), parenttable])

        # Compile the whole thing and return the results
        stringbuf = StringIO.StringIO()
        doc = SimpleDocTemplate(stringbuf,
                                bottomMargin=.5 * inch,
                                topMargin=.5 * inch,
                                rightMargin=.5 * inch,
                                leftMargin=.5 * inch)
        doc.build(components)
        return stringbuf.getvalue()
예제 #23
0
def HeaderFooterPersona(canvas, doc):
    canvas.saveState()
    title = "Reporte de Personas"
    canvas.setTitle(title)

    Story = []
    styles = getSampleStyleSheet()

    archivo_imagen = finders.find('assets/img/logo.jpg')
    canvas.drawImage(archivo_imagen,
                     30,
                     720,
                     width=540,
                     height=100,
                     preserveAspectRatio=True)

    fecha = datetime.now().strftime('%d/%m/%Y ')
    # Estilos de Párrafos
    ta_c = ParagraphStyle(
        'parrafos',
        alignment=TA_CENTER,
        fontSize=10,
        fontName="Helvetica",
    )
    ta_l = ParagraphStyle(
        'parrafos',
        alignment=TA_LEFT,
        fontSize=13,
        fontName="Helvetica-Bold",
    )
    ta_l7 = ParagraphStyle(
        'parrafos',
        alignment=TA_LEFT,
        fontSize=7,
        fontName="Helvetica-Bold",
    )
    ta_r = ParagraphStyle(
        'parrafos',
        alignment=TA_RIGHT,
        fontSize=13,
        fontName="Helvetica-Bold",
    )

    # Header
    header = Paragraph(
        "REPORTE DE PERSONAS ",
        ta_l,
    )
    w, h = header.wrap(doc.width + 250, doc.topMargin)
    header.drawOn(canvas, 215, doc.height - 10 + doc.topMargin - 80)

    #header1 = Paragraph("<u>DIRECCIÓN DE AGRICULTURA Y TIERRA</u> ",ta_r,)
    #w,h = header1.wrap(doc.width-115, doc.topMargin)
    #header1.drawOn(canvas, 140, doc.height -10 + doc.topMargin - 2)

    P1 = Paragraph('''N°''', ta_c)
    P2 = Paragraph('''CEDULA''', ta_c)
    P3 = Paragraph('''NOMBRE''', ta_c)
    P4 = Paragraph('''APELLIDO''', ta_c)
    P5 = Paragraph('''CORREO''', ta_c)
    P6 = Paragraph('''ROL''', ta_c)
    data = [[P1, P2, P3, P4, P5, P6]]
    header2 = Table(data, colWidths=[35, 85, 80, 80, 150, 80])
    header2.setStyle(
        TableStyle([
            ('GRID', (0, -1), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), '#50b7e6'),
            ('ALIGN', (0, 0), (-1, -3), "CENTER"),
        ]))
    w, h = header2.wrap(doc.width - 115, doc.topMargin)
    header2.drawOn(canvas, 42.5, doc.height - 40 + doc.topMargin - 93)

    # FOOTER

    footer4 = Paragraph("Fecha: " + str(fecha), ta_l7)
    w, h = footer4.wrap(doc.width - 200, doc.bottomMargin)
    footer4.drawOn(canvas, doc.height - 105, doc.topMargin + 620, h)

    canvas.restoreState()
예제 #24
0
def generate_pdf_geyser(client, system, order):
    best_three_prices, product, supplier = pricing.QuotationChargesGeyser(
        5).get_prices()
    status_response = 2
    formatted_time = time.ctime()
    try:
        for i in range(3):
            pdf_file_generate = str(system.order_number)
            slips_dir = 'app/static/app/slips/'
            document = SimpleDocTemplate(slips_dir +
                                         pdf_file_generate + "_" + str(i + 1) + ".pdf",
                                         pagesize=letter,
                                         rightMargin=72, leftMargin=72,
                                         topMargin=72, bottomMargin=18)
            elements = []
            logo = "app/static/common/icon.png"

            image = Image(logo, 2 * inch, 2 * inch)
            elements.append(image)

            styles = getSampleStyleSheet()
            styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
            styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
            styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))

            ptext = '<font size=12>%s</font>' % formatted_time

            elements.append(Paragraph(ptext, styles["Right"]))
            elements.append(Spacer(1, 12))

            ptext = '<font size=12>Dear %s</font>' % client.firstname.capitalize()
            elements.append(Paragraph(ptext, styles["Normal"]))
            elements.append(Spacer(1, 12))
            ptext = '<font size=12>' \
                    'The document quotation is provided for the item requested below ' \
                    '</font>'

            elements.append(Paragraph(ptext, styles["Justify"]))
            elements.append(Spacer(1, 12))

            ptext = '<font size=12>Thank you very much and we look forward to ' \
                    'serving you.</font>'

            elements.append(Paragraph(ptext, styles["Justify"]))
            elements.append(Spacer(1, 12))

            ptext = '<font size=12>Sincerely,</font>'
            elements.append(Paragraph(ptext, styles["Normal"]))
            elements.append(Spacer(1, 48))

            ptext = '<font size=16>Personal Details</font>'
            elements.append(Paragraph(ptext, styles["Center"]))
            elements.append(Spacer(1, 12))

            data = [['Email', client.username.upper()],
                    ['First Name', client.firstname.upper()],
                    ['Last Name', client.lastname.upper()],
                    ['Contact Number', client.contact_number.upper()],
                    ['Physical Address',
                     client.physical_address.building_name.upper() + '\n' +
                     client.physical_address.street_name.upper() + '\n' +
                     client.physical_address.city.upper() + '\n' +
                     client.physical_address.suburb.upper() + '\n' +
                     str(client.physical_address.zip_code)]]

            table = Table(data, colWidths=190)
            table.setStyle(TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

            elements.append(table)
            elements.append(Spacer(1, 24))
            ptext = '<font size=16 style="text-transform:uppercase">System ' \
                    'Details</font></center>'
            elements.append(Paragraph(ptext, styles["Center"]))
            elements.append(Spacer(1, 12))
            data = [['Order number', str(system.order_number).upper()[:10]],
                    ['Number of Users', order.users_number],
                    ['Need Finance', str(system.need_finance).upper()],
                    ['Required Geyser Size',
                     str(order.required_geyser_size).upper()],
                    ['Water Collector', str(order.water_collector)],
                    ['Include Instalation', str(
                        system.include_installation).upper()],
                    ['Property Type', order.property_type.upper()],
                    ['Roof Inclination', order.roof_inclination.upper()],
                    ]

            table = Table(data, colWidths=190)
            table.setStyle(TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ]))

            elements.append(table)
            elements.append(Spacer(1, 24))

            try:
                data = []
                ptext = '<font size=16 style="text-transform:uppercase">Supplier ' \
                        'Details</font></center>'
                elements.append(Paragraph(ptext, styles["Center"]))
                elements.append(Spacer(1, 12))
                data.append(['Company Name', str(supplier[i].company_name).upper()])
                data.append(['Contact Number', str(supplier[i].contact_number).upper()])
                data.append(['Web Address',
                         str(supplier[i].web_address).upper()])
                table = Table(data, colWidths=190)
                table.setStyle(TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))

                elements.append(table)
            except:
                ptext = '<font size=12 style="text-transform:uppercase">' \
                        'We have fewer suppliers for this Item ' \
                        'We are trying to provide you with ' \
                        'best prices. Thank you for your ' \
                        'understanding</font></center>'
                elements.append(Paragraph(ptext, styles["Center"]))

            elements.append(Spacer(1, 24))

            elements.append(Spacer(1, 24))
            try:
                ptext = '<font size=16 style="text-transform:uppercase">Charges ' \
                        '</font></center>'
                elements.append(Paragraph(ptext, styles["Center"]))
                elements.append(Spacer(1, 12))
                data_ = []
                data_.append(['Amount ', 'R' + str(best_three_prices[i].price).upper()])
                data_.append(['Items ', str(product).upper()])
                table = Table(data_, colWidths=190)
                table.setStyle(TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))

                elements.append(table)
            except :
                print(" Amount UnAvailable")
            elements.append(Spacer(1, 24))

            ptext = '<font size=12> Powered by \
                     <a href="http://www.itechhub.co.za" color="blue">iTechHub</a>\
                     </font>'

            elements.append(Paragraph(ptext, styles["Center"]))
            document.build(elements)
            status_response = 1
    except:
        print("No Prices Available from Suppliers")

    return pdf_file_generate, status_response
예제 #25
0
def generate_pdf(month):
    '''Generates pdf file in project/downloads directory
    :param month: Month model instance
    :return: path to new file'''
    data = []   # data aka body of pdf
    
    # paragraph styles
    stylesheet = getSampleStyleSheet()
    normal_style = stylesheet['Normal']
    title_style = stylesheet['Heading1']
    title_style.alignment = 1

    title = Paragraph(f'{MONTHS[month.month][1]} {month.year}', title_style)    # title
    data.append(title)

    data.append(Spacer(500, 15))                                                # spacer

    # data for table
    table_data = [
        [
            Paragraph('<b>Amount</b>', normal_style),
            Paragraph('<b>Category</b>', normal_style),                         # headers
            Paragraph('<b>Description</b>', normal_style)
        ],                                                                      # expenses
        *[(exp.amount, exp.category, Paragraph(exp.description, normal_style)) for exp in month.expenses],
    ]

    # styles for table
    styles = TableStyle([
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
        ('BACKGROUND', (0,0), (-1,0), colors.lavenderblush),
    ])

    # build and append table
    table = Table(table_data, (60, 80, 350))
    table.setStyle(styles)
    data.append(table)

    data.append(Spacer(500, 30))    # spacer

    # preparing summary data
    CAT_NAMES = [el[1] for el in CATEGORIES]
    summary = db.session.query(db.func.sum(Expense.amount)).filter_by(month_id=month.id)
    sums = [
        (summary.filter_by(category=c).first()[0], c) for c in CAT_NAMES
    ]
    sums.append((summary.first()[0], 'Total'))

    # summary table data
    sum_table_data = [
        [Paragraph('<b>Total Amount</b>', normal_style), Paragraph('<b>Category</b>', normal_style)],
        *sums
    ]

    # summary table styles
    sum_styles = TableStyle([
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
        ('BACKGROUND', (0,0), (-1,0), colors.lavenderblush)
    ])

    # build and append table
    sum_table = Table(sum_table_data)
    sum_table.setStyle(sum_styles)
    data.append(sum_table)

    # build pdf
    file_path = os.path.join(DOWNLOADS_PATH, f'{month.user_id}.pdf')
    doc = SimpleDocTemplate(file_path)
    doc.build(data)
    return file_path
예제 #26
0
    def pdf_body(self, data, number):
        stylesheet = Styles.getSampleStyleSheet()

        TitleStyle = stylesheet[self.styles['title']['name']]
        TitleStyle.alignment = self.styles['title']['align']

        SummaryStyle = stylesheet[self.styles['summary']['name']]
        SummaryStyle.alignment = self.styles['summary']['align']

        CVEStyle = stylesheet[self.styles['cve']['name']]
        CVEStyle.alignment = self.styles['cve']['align']

        CVEInfoStyle = stylesheet[self.styles['cve_info']['name']]
        CVEInfoStyle.alignment = self.styles['cve_info']['align']

        CVEDescStyle = stylesheet[self.styles['cve_description']['name']]
        CVEDescStyle.alignment = self.styles['cve_description']['align']

        CVELinksStyle = stylesheet[self.styles['cve_link']['name']]
        CVELinksStyle.alignment = self.styles['cve_link']['align']

        body = list()
        body.append(Paragraph(
            '{} #{}'.format(self.template['title'], number), TitleStyle))

        body.append(Spacer(Units.inch, Units.inch/4))

        body.append(Paragraph(self.template['description'], SummaryStyle))

        body.append(Spacer(Units.inch, Units.inch/4))

        cve_table, text = self.parse_json(data)

        table = Table(cve_table)
        table.setStyle(TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, Colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, Colors.black)
        ]))

        body.append(table)

        body.append(PageBreak())

        for i in text:
            body.append(Paragraph(i['label'], CVEStyle))
            body.append(Paragraph('Description:', CVEInfoStyle))
            body.append(Paragraph(i['description'], CVEDescStyle))
            body.append(Paragraph('External Links:', CVEInfoStyle))
            body.append(Paragraph(
                '* <font color="{}">NIST</font>: <font color="{}">{}</font>'
                    .format(self.styles['cve_label_color'],
                            self.styles['cve_link_color'],
                            self.template['nist_url'].format(i['name'])),
                CVELinksStyle))
            body.append(Paragraph(
                '* <font color="{}">MITRE</font>: <font color="{}">{}</font>'
                    .format(self.styles['cve_label_color'],
                            self.styles['cve_link_color'],
                            self.template['mitre_url'].format(i['name'])),
                CVELinksStyle))
            for link in i['reference']:
                body.append(Paragraph(
                    '* <font color="{}">{}</font>'
                        .format(self.styles['cve_link_color'], link),
                    CVELinksStyle))
            body.append(Spacer(Units.inch, Units.inch/4))

        return body
예제 #27
0
    def draw_course_info(self, y_pos):
        """
        Draws the main table containing the data items.
        """
        course_items_data = [[
            '', (_('Description')), (_('Quantity')),
            (_('List Price\nper item')), (_('Discount\nper item')),
            (_('Amount')), ''
        ]]
        for row_item in self.items_data:
            course_items_data.append([
                '',
                Paragraph(row_item['item_description'],
                          getSampleStyleSheet()['Normal']),
                row_item['quantity'], '{currency}{list_price:.2f}'.format(
                    list_price=row_item['list_price'],
                    currency=self.currency), '{currency}{discount:.2f}'.format(
                        discount=row_item['discount'], currency=self.currency),
                '{currency}{item_total:.2f}'.format(
                    item_total=row_item['item_total'],
                    currency=self.currency), ''
            ])

        padding_width = 7 * mm
        desc_col_width = 60 * mm
        qty_col_width = 26 * mm
        list_price_col_width = 21 * mm
        discount_col_width = 21 * mm
        amount_col_width = 40 * mm
        course_items_table = Table(course_items_data, [
            padding_width, desc_col_width, qty_col_width, list_price_col_width,
            discount_col_width, amount_col_width, padding_width
        ],
                                   splitByRow=1,
                                   repeatRows=1)

        course_items_table.setStyle(
            TableStyle([
                #List Price, Discount, Amount data items
                ('ALIGN', (3, 1), (5, -1), 'RIGHT'),

                # Amount header
                ('ALIGN', (5, 0), (5, 0), 'RIGHT'),

                # Amount column (header + data items)
                ('RIGHTPADDING', (5, 0), (5, -1), 7 * mm),

                # Quantity, List Price, Discount header
                ('ALIGN', (2, 0), (4, 0), 'CENTER'),

                # Description header
                ('ALIGN', (1, 0), (1, -1), 'LEFT'),

                # Quantity data items
                ('ALIGN', (2, 1), (2, -1), 'CENTER'),

                # Lines below the header and at the end of the table.
                ('LINEBELOW', (0, 0), (-1, 0), 1.00, '#cccccc'),
                ('LINEBELOW', (0, -1), (-1, -1), 1.00, '#cccccc'),

                # Innergrid around the data rows.
                ('INNERGRID', (1, 1), (-2, -1), 0.50, '#cccccc'),

                # Entire table
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('TOPPADDING', (0, 0), (-1, -1), 2 * mm),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2 * mm),
                ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            ]))
        rendered_width, rendered_height = course_items_table.wrap(0, 0)
        table_left_padding = (self.page_width - rendered_width) / 2

        split_tables = course_items_table.split(
            0, self.first_page_available_height)
        if len(split_tables) > 1:
            # The entire Table won't fit in the available space and requires splitting.
            # Draw the part that can fit, start a new page
            # and repeat the process with the rest of the table.
            split_table = split_tables[0]
            __, rendered_height = split_table.wrap(0, 0)
            split_table.drawOn(self.pdf, table_left_padding,
                               y_pos - rendered_height)

            self.prepare_new_page()
            split_tables = split_tables[1].split(
                0, self.second_page_available_height)
            while len(split_tables) > 1:
                split_table = split_tables[0]
                __, rendered_height = split_table.wrap(0, 0)
                split_table.drawOn(
                    self.pdf, table_left_padding,
                    self.second_page_start_y_pos - rendered_height)

                self.prepare_new_page()
                split_tables = split_tables[1].split(
                    0, self.second_page_available_height)
            split_table = split_tables[0]
            __, rendered_height = split_table.wrap(0, 0)
            split_table.drawOn(self.pdf, table_left_padding,
                               self.second_page_start_y_pos - rendered_height)
        else:
            # Table will fit without the need for splitting.
            course_items_table.drawOn(self.pdf, table_left_padding,
                                      y_pos - rendered_height)

        if not self.is_on_first_page():
            y_pos = self.second_page_start_y_pos

        return y_pos - rendered_height - self.min_clearance
예제 #28
0
def _build_invoices(prestations, invoice_number, invoice_date, accident_id,
                    accident_date):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    # import pydevd; pydevd.settrace()
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patientFirstName = ''
    patientAddress = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net',
                 'Heure', 'P. Pers', 'Executant'))
    pytz_luxembourg = pytz.timezone("Europe/Luxembourg")
    for presta in prestations:
        patient = presta.invoice_item.patient
        patientSocNumber = patient.code_sn
        patientNameAndFirstName = patient
        patientName = patient.name
        patientFirstName = patient.first_name
        patientAddress = patient.address
        patientZipCode = patient.zipcode
        patientCity = patient.city
        if presta.carecode.reimbursed:
            i += 1
            data.append(
                (i, presta.carecode.code,
                 (pytz_luxembourg.normalize(presta.date)).strftime('%d/%m/%Y'),
                 '1', presta.carecode.gross_amount(presta.date),
                 presta.carecode.net_amount(
                     presta.date, patient.is_private,
                     (patient.participation_statutaire and patient.age > 18)),
                 (pytz_luxembourg.normalize(presta.date)).strftime('%H:%M'),
                 "", presta.employee.provider_code))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if (y % 10 == 0 and y != 0):
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            newData.append(
                ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', ''))
    newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4),
                    _compute_sum(data[1:], 5), '', '', ''))

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n' +
            "{0}\n{1}\n{2}\n{3}".format(
                config.NURSE_NAME, config.NURSE_ADDRESS,
                config.NURSE_ZIP_CODE_CITY, config.NURSE_PHONE_NUMBER),
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n{0}'.format(
                config.MAIN_NURSE_CODE)
        ],
        [
            u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) +
            "\n" + u'Nom et Pr' + smart_text("e") +
            u'nom du patient: %s' % smart_text(patientNameAndFirstName),
            u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' +
            smart_text(u"é") +
            u'nom: %s' % smart_text(patientFirstName.strip()) + '\n' +
            u'Rue: %s' % patientAddress.strip() + '\n' +
            u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_text(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    elements.append(
        Paragraph(
            u"Mémoire d'Honoraires Num. %s en date du : %s" %
            (invoice_number, invoice_date), styles['Center']))
    elements.append(Spacer(1, 18))

    elements.append(table)

    _2derniers_cases = Table([["", "Paiement Direct"]], [1 * cm, 4 * cm],
                             1 * [0.5 * cm],
                             hAlign='LEFT')
    _2derniers_cases.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (0, 0), 0.75, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    elements.append(Spacer(1, 18))

    elements.append(_2derniers_cases)
    _2derniers_cases = Table([["", "Tiers payant"]], [1 * cm, 4 * cm],
                             1 * [0.5 * cm],
                             hAlign='LEFT')
    _2derniers_cases.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (0, 0), 0.75, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))
    elements.append(Spacer(1, 18))
    elements.append(_2derniers_cases)
    elements.append(Spacer(1, 18))

    _pouracquit_signature = Table(
        [["Pour acquit, le:", "Signature et cachet"]], [10 * cm, 10 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')

    elements.append(_pouracquit_signature)
    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patientFirstName,
        "invoice_amount": newData[23][5]
    }
예제 #29
0
파일: coverpages.py 프로젝트: super11/hplip
def createUrgentCoverPage(page_size=PAGE_SIZE_LETTER,
                          total_pages=1,
                          recipient_name='',
                          recipient_phone='',
                          recipient_fax='',
                          sender_name='',
                          sender_phone='',
                          sender_fax='',
                          sender_email='',
                          regarding='',
                          message='',
                          preserve_formatting=False,
                          output=None):

    s = getSampleStyleSheet()

    story = []
    i = Image(os.path.join(prop.image_dir, 'other', 'urgent_title.png'),
              width=424,
              height=92)
    i.hAlign = 'LEFT'
    story.append(i)
    story.append(Spacer(1, inch))
    story.append(HRFlowable(width='100%', color='black'))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [
        [recipient_name_label, recipient_name_text],
        [recipient_fax_label, recipient_fax_text],
        ['', ''],
        [sender_name_label, sender_name_text],
        [sender_phone_label, sender_phone_text],
        [sender_email_label, sender_email_text],
        ['', ''],
        [date_time_label, date_time_text],
        [total_pages_label, total_pages_text],
        [regarding_label, regarding_text],
    ]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(Table(data, style=LIST_STYLE))
    story.append(HRFlowable(width='100%', color='black'))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            #('SPAN', (-2, 1), (-1, -1)),
        ])

        #story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        #        if preserve_formatting:
        #            message = '\n'.join(message[:2048].splitlines()[:32])
        #
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Preformatted(escape(message), ps)],]
        #        else:
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Paragraph(escape(message[:2048]), ps), ''],]
        #
        #        #story.append(HRFlowable(width='100%', color='black'))
        #        #story.append(Table(data, style=MSG_STYLE))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])
            story.append(Preformatted(escape(message), ps))
        else:
            story.append(Paragraph(escape(message), ps))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
예제 #30
0
def write_pdf_view(request, pk_operativo):

    #pk_operativo = request.POST.get("pk_operativo")
    operativo = Operativo.objects.get(pk=pk_operativo)
    entregas = Entrega.objects.filter(operativo=pk_operativo)

    doc = SimpleDocTemplate("/tmp/somefilename.pdf", pagesize=portrait(A4))
    Story = []
   
    ps = ParagraphStyle('parrafos',
                           alignment = TA_CENTER,
                           fontSize = 12,
                           fontName="Times-Roman")

    text = "<b>REPORTE DE ENTREGAS DE ALIMENTOS</b>"
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.5*inch))
    
    ps = ParagraphStyle('parrafos',
                           alignment = TA_JUSTIFY,
                           fontSize = 10,
                           fontName="Times-Roman")
    nentregadas = 0
    for entrega in entregas:
        nentregadas = nentregadas + entrega.nbolsas
    text = "<b>Fecha: </b>{}".format(operativo.fecha)
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.05*inch))
    text = "<b>Proveedor: </b>{}".format(operativo.proveedor)
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.05*inch))
    text = "<b>Responsable: </b>{}".format(operativo.responsable)
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.05*inch))
    text = "<b>Bolsas recibidas: </b>{} <b>Bolsas entregadas: </b>{} <b>Bolsas sobrantes: </b>{}".format(operativo.nbolsas, nentregadas, operativo.nbolsas-nentregadas)
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.4*inch))

    ps = ParagraphStyle('parrafos',
                           alignment = TA_JUSTIFY,
                           fontSize = 11,
                           fontName="Times-Roman")

    text = "<b>Beneficiarios especiales: </b>"
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.2*inch))

    ps = ParagraphStyle('parrafos',
                           alignment = TA_JUSTIFY,
                           fontSize = 8,
                           fontName="Times-Roman")


    titles = [
        Paragraph('N° bolsas', ps),
        Paragraph('CI', ps),
        Paragraph('Beneficiario', ps),
        Paragraph('Comision', ps),
        Paragraph('Observacion', ps),
    ]
    despachos_formated = [titles]

    nentregas = 0
    for entrega in entregas:
        if (entrega.especial == 1):
            beneficiario = Beneficiarios.objects.get(pk=entrega.beneficiario.pk)
            nbolsas = Paragraph(str(entrega.nbolsas), ps) 
            nombres = Paragraph(beneficiario.nombres, ps) 
            cedula = Paragraph(beneficiario.pk, ps)
            if (entrega.comision_servicio == 1):
                comision = Paragraph("SI", ps)
            else: 
                comision = Paragraph("No", ps) 
            observacion = Paragraph(entrega.observacion, ps)  
            nentregas = nentregas + entrega.nbolsas
            despachos_formated.append([nbolsas, cedula, nombres, comision, observacion])

    despachos_formated.append(["Total: {}".format(nentregas), "", "", ""])
    t=Table(despachos_formated, (45,50,200,45,150))
    t.setStyle(TableStyle([
        ('BACKGROUND',(0,0),(5,0),colors.lightgrey),
        ('INNERGRID',(0,0),(5,0), 0.25, colors.gray),
        ('BOX',(0,0),(5,0), 0.25, colors.gray)
    ]))

    Story.append(t)
    Story.append(Spacer(1,0.2*inch))
    ps = ParagraphStyle('parrafos',
                           alignment = TA_JUSTIFY,
                           fontSize = 11,
                           fontName="Times-Roman")

    text = "<b>Beneficiarios: </b>"
    p = Paragraph(text, ps)
    Story.append(p)
    Story.append(Spacer(1,0.2*inch))

    ps = ParagraphStyle('parrafos',
                           alignment = TA_JUSTIFY,
                           fontSize = 8,
                           fontName="Times-Roman")

    titles = [
        Paragraph('N° bolsas', ps),
        Paragraph('CI', ps),
        Paragraph('Beneficiario', ps),
        Paragraph('Observacion', ps),
    ]
    despachos_formated = [titles]

    nentregas = 0
    for entrega in entregas:
        if (entrega.especial == 0):
            beneficiario = Beneficiarios.objects.get(pk=entrega.beneficiario.pk)
            nbolsas = Paragraph(str(entrega.nbolsas), ps), 
            nombres = Paragraph(beneficiario.nombres, ps),  
            cedula = Paragraph(beneficiario.pk, ps),  
            observacion = Paragraph(entrega.observacion, ps), 
            nentregas = nentregas + entrega.nbolsas
            despachos_formated.append([nbolsas, cedula, nombres, observacion])
            nentregas = nentregas + entrega.nbolsas
    despachos_formated.append(["Total: {}".format(nentregas), "", "", ""])

    t=Table(despachos_formated, (45, 50,230,150))
    t.setStyle(TableStyle([
        ('BACKGROUND',(0,0),(3,0),colors.lightgrey),
        ('INNERGRID',(0,0),(3,0), 0.25, colors.gray),
        ('BOX',(0,0),(3,0), 0.25, colors.gray)
        ]))

    Story.append(t)

    doc.build(Story, header)

    fs = FileSystemStorage("/tmp")
    with fs.open("somefilename.pdf") as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename="somefilename.pdf"'
        return response

    return response