Ejemplo n.º 1
0
def travel_pdf(request, response, file_name):
    """Method to generate pdf."""
    try:
        rid = 5
        fnames = file_name.split('_')
        travel_id = int(fnames[2])
        tid = '{0:05d}'.format(travel_id)
        # Get some parameters
        travel = get_travel(request, travel_id)
        tarehe = travel.travel_date
        report_name = 'SNo. %s - Travel Authorization ' % (tid)
        region = 'National'
        dates = 'Date %s' % (tarehe.strftime("%d, %B %Y"))
        styles = get_styles()
        element = []
        get_header(element, report_name, region, dates, styles)
        # Write the data
        get_travel_details(request, element, travel)
        doc = SimpleDocTemplate(
            response, pagesize=A4, rightMargin=20,
            leftMargin=20, topMargin=30, bottomMargin=36.5,
            keywords="CPIMS, Child Protection in Kenya, UNICEF, DCS, <!NMA!>")
        if rid in [1, 3, 4, 5]:
            doc.pagesize = landscape(A4)
        element.append(Spacer(0.1 * cm, .2 * cm))
        # doc.build(element)
        doc.watermark = 'CPIMS'
        doc.fund_name = ''
        doc.report_info = ''
        doc.source = 'Child Protection Information Management System (CPIMS)'
        doc.build(element, onFirstPage=draw_page, onLaterPages=draw_page,
                  canvasmaker=Canvas)
    except Exception as e:
        raise e
    else:
        pass
Ejemplo n.º 2
0
def write_document(response, file_name, params={}):
    """Method to write to pdf from pandas."""
    try:

        # datas = pd.DataFrame(data)
        # response = '%s.pdf' % (file_name)
        STATIC_ROOT = settings.STATICFILES_DIRS[0]
        rparams = file_name.split('_')
        rid = int(rparams[3])
        region = rparams[0].replace('-', ' ')
        report_name = rparams[1].replace('-', ' ')
        if 'OU ' in region or 'ou_name' in params:
            ou_name = params['ou_name'] if 'ou_name' in params else 'DCS'
            report_name = "%s (%s)" % (report_name, ou_name)
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
        styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
        styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
        styles.add(ParagraphStyle(
            name='Line_Data', alignment=TA_LEFT, fontSize=8,
            leading=11, fontColor='#FFFFFF'))
        styles.add(ParagraphStyle(
            name='Line_Data_Small', alignment=TA_LEFT,
            fontSize=7, leading=8))
        styles.add(ParagraphStyle(
            name='Line_Data_Large', alignment=TA_LEFT,
            fontSize=12, leading=15))
        styles.add(ParagraphStyle(
            name='Line_Data_Largest', alignment=TA_LEFT,
            fontSize=14, leading=15))
        styles.add(ParagraphStyle(
            name='Line_Label', font='Helvetica-Bold',
            fontSize=7, leading=6, alignment=TA_LEFT))
        styles.add(ParagraphStyle(
            name='Line_Label1', font='Helvetica-Bold', fontSize=7,
            leading=6, alignment=TA_RIGHT))
        styles.add(ParagraphStyle(
            name='Line_Label_Center', font='Helvetica-Bold',
            fontSize=12, alignment=TA_CENTER))
        element = []
        datenow = datetime.now()
        tarehe = datenow.strftime("%d, %b %Y %I:%M %p")
        url = 'https://childprotection.go.ke'
        # ous = get_data(rid)
        # col_size = len(df.columns)
        # dt_size = len(df.index)
        # Handle headers
        address = '<b>MINISTRY OF LABOUR AND SOCIAL PROTECTION'
        address += "<br />STATE DEPARTMENT FOR SOCIAL PROTECTION"
        address += "<br />DEPARTMENT OF CHILDREN'S SERVICES</b>"
        report_number = '%s\n%s CPIMS Report\n%s' % (url, report_name, tarehe)
        # Work on the data
        start_date = ''
        end_date = datenow.strftime("%d, %B %Y")
        mon = int(datenow.strftime("%m"))
        year = int(datenow.strftime("%Y"))
        fyear = year - 1 if mon < 7 else year
        if rid in [1, 2, 4]:
            start_date = '1, July %s to ' % (fyear)
        dates = '%s%s' % (start_date, end_date)
        bar_code = BarCode(value='%s' % (report_number))
        # Logo
        logo = "%s/img/logo_gok.png" % (STATIC_ROOT)
        sd = Image(logo)
        sd.drawHeight = 0.6 * inch
        sd.drawWidth = 0.7 * inch
        data1 = [[sd, Paragraph(address, styles["Line_Data_Large"]),
                  Paragraph('CPIMS %s Report' % (region),
                            styles["Line_Data_Large"]), bar_code],
                 ['', '', Paragraph(dates,
                                    styles["Line_Label"]), '']]
        tt = Table(
            data1, colWidths=(2.1 * cm, None, 5.9 * cm, 3.4 * cm,),
            rowHeights=(1.2 * cm, .5 * cm,))

        tt.setStyle(TableStyle([
            ('INNERGRID', (2, 0), (2, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
        rnote = '<b>NOTE: This is a computer generated report <br /> '
        rnote += ' as at %s.</b>' % (tarehe)
        element.append(tt)
        element.append(Spacer(0.1 * cm, .2 * cm))
        data1 = [[Paragraph('Report<br />Name:', styles["Line_Label"]),
                  Paragraph(report_name, styles["Line_Data_Largest"]),
                  Paragraph(rnote, styles["Line_Data_Small"]), ]]

        t0 = Table(data1, colWidths=(2 * cm, None, 6.1 * cm,))
        t0.setStyle(TableStyle([
            ('INNERGRID', (1, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

        element.append(t0)
        # print(type(col_size), col_size)
        style = TableStyle(
            [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
             ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
             ('ALIGN', (2, 3), (-1, -1), 'RIGHT'),
             ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])
        # Configure columns
        flts = 0
        cols, idx = get_pivot_vars(rid)
        # print(len(cols), len(idx), cols, idx)
        mflts = {}
        ou_id = params['ou_id'] if 'ou_id' in params else 0
        if rid == 4:
            mflts = {'ou_id': ou_id}
        dfs, odf = create_pivot(rid, idx, cols, flts, mflts)
        # datas = np.vstack((list(dfs), np.array(dfs))).tolist()
        dt_size = len(dfs.index)
        col_size = len(dfs.columns)
        hdx = len(idx)
        rdx = len(cols)
        print('Size of Index / Columns', dt_size, col_size)
        # Now prepare the data
        if col_size > 2:
            pvt_names = list(dfs.reset_index().columns.names)
            dcols = {}
            dsize = len(dfs.columns.values)
            pvt_values = list(dfs.reset_index().columns.values)
            hd_len = len(pvt_names)
            # titles = list(pvt_values[0]) + pvt_names
            col_length = 0
            for col in pvt_values:
                col_length = len(col)
                break
            for i in range(0, col_length):
                for col in pvt_values:
                    if i not in dcols:
                        dcols[i] = [col[i]]
                    else:
                        dcols[i].append(col[i])
            fcls = []
            for fc in dcols:
                fl = dcols[fc]
                if fc == 0:
                    fcl = list(dict.fromkeys(fl))
                    nfcl = fcl + [''] * (len(fl) - len(fcl))
                    fcls.append(nfcl)
                else:
                    fcls.append(fl)
            data_list = dfs.reset_index().values.tolist()
            # data_list = [dfs.columns.values.tolist()] + dfs.values.tolist()
            # print(data_list)
            dtl, dd = [], []
            for dl in data_list:
                # dl[1] = Paragraph(dl[1], styles["Normal"])
                if dl[0] not in dd:
                    dd.append(dl[0])
                    # dl[0] = Paragraph(dl[0], styles["Normal"])
                    dtl.append(dl)
                else:
                    dl[0] = ''
                    dtl.append(dl)

            datas = fcls + dtl
            cols = get_rlcols(rid, dsize)
            # Create table style
            bs = col_size + (hdx - 1)
            ds = dt_size + (rdx)
            style = TableStyle(
                [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                 ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                 ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                 ('ALIGN', (hdx, hd_len), (-1, -1), 'RIGHT'),
                 # ('FONTSIZE', (0, 0), (-1, -1), 9),
                 ('FONTNAME', (0, ds), (-1, -1), 'Helvetica-Bold'),
                 ('FONTNAME', (bs, 0), (-1, -1), 'Helvetica-Bold'),
                 ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])

            t1 = Table(datas, colWidths=cols, repeatRows=hd_len)
            t1.setStyle(style)
            element.append(t1)
        else:
            ftxt = TXT[3]
            bfooter = Paragraph(ftxt, styles["Line_Data_Largest"])
            element.append(Spacer(0.1 * cm, 1.1 * cm))
            element.append(bfooter)
        qstyle = TableStyle(
            [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
             ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
             ('SPAN', (0, 0), (-1, 0)),
             ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
             ('FONTNAME', (0, 0), (-1, 1), 'Helvetica-Bold'),
             ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])
        element.append(Spacer(0.1 * cm, 1.5 * cm))
        if rid == 4 and col_size > 2:
            # Add case management details
            cmdts = get_cm(rid, ou_id)
            cmsize = len(cmdts.index)
            cmgt = "This Week's Summons, Court Sessions and Discharges"
            if cmsize > 0:
                cm_values = cmdts.values.tolist()
                colw = (2.86 * cm, 4.0 * cm, 1.0 * cm, 5.0 * cm,
                        6.0 * cm, 6.0 * cm, 3.0 * cm)
                data = ["CPIMS ID", "Name / Initials", "Age", "DoB",
                        "Case Category", "Case Management", "Due Date"]
                cm_data = [[cmgt, "", "", "", "", "", ""], data]
                cm_data += cm_values
            else:
                colw = (2.86 * cm, 25.0 * cm)
                data = ["", "No data available from the System."]
                cm_data = [[cmgt, ""], data]

            t2 = Table(cm_data, colWidths=colw, repeatRows=2)
            t2.setStyle(qstyle)
            element.append(t2)
            element.append(Spacer(0.1 * cm, .5 * cm))
            ftxt = TXT[1]
            footer = Paragraph(ftxt % (cmsize), styles["Line_Data_Small"])
            element.append(footer)
            element.append(Spacer(0.1 * cm, .6 * cm))
            # Also add DQA details
            qdts = get_dqa(odf)
            qdsize = len(qdts.index)
            if qdsize > 0:
                qa_values = qdts.values.tolist()
                # print(qa_values)
                dtitle = "DQA Records for your action"
                colw = (2.86 * cm, 4.0 * cm, 1.0 * cm, 5.0 * cm, 3.0 * cm,
                        3.0 * cm, 3.0 * cm, 3.0 * cm, 3.0 * cm)
                qdata = ["CPIMS ID", "Name / Initials", "Age",
                         "Case Category", "DQA Sex", "DQA DoB",
                         "DQA Age", "Case Status", "Case Date"]
                dq_data = [[dtitle, "", "", "", "", "", "", "", ""], qdata]
                dq_data += qa_values
            else:
                colw = (2.86 * cm, 25.0 * cm)
                qdata = ["", "No data available from the System."]
                dq_data = [["DQA Records for your action", ""], qdata]
            t3 = Table(dq_data, colWidths=colw, repeatRows=2)
            t3.setStyle(qstyle)
            element.append(t3)
            element.append(Spacer(0.1 * cm, .5 * cm))
            ftxt = TXT[2]
            footer = Paragraph(ftxt % (qdsize), styles["Line_Data_Small"])
            element.append(footer)
        doc = SimpleDocTemplate(
            response, pagesize=A4, rightMargin=20,
            leftMargin=20, topMargin=30, bottomMargin=30,
            keywords="CPIMS, Child Protection in Kenya, UNICEF, DCS, <!NMA!>")
        doc.pagesize = landscape(A4)
        # doc.build(element)
        doc.watermark = 'CPIMS'
        doc.fund_name = ''
        doc.report_info = ''
        doc.source = 'Child Protection Information Management System (CPIMS)'
        doc.build(element, onFirstPage=draw_page, onLaterPages=draw_page,
                  canvasmaker=Canvas)
    except Exception as e:
        print('Error generating pdf - %s' % (e))
    else:
        pass