def report_internal_faculty_cv_pdf(request, instructor):
    def make_table(data, widths, style=[]):
        table = LongTable(data, colWidths=widths)
        table.setStyle(TableStyle(style))
        return table 
        
    response = HttpResponse(mimetype='application/pdf')
    
    buffer = BytesIO() 
    
    org = Internal()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    styleBC = copy.copy(styleB)
    styleBC.alignment = TA_CENTER 
    
    width, height = A4
    doc = FooterDocTemplate(buffer, pagesize=(height, width))
    
    frame = org.getFrame(doc)
    template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer(doccode="NCEAC.DOC.008", pagesize=(width, height)))
    doc.addPageTemplates([template])
    
    # Our main content holder 
    
    elements = []
    
    i = instructor 
    ip = i.instructorprofile
    percent_time_teaching = ip.percent_time_teaching
    
    # title page 
    data = [[Paragraph('Name', styleB), i.name],
            [Paragraph('Academic Rank', styleB), ip.designation],
            [Paragraph('Administrative Responsibility', styleB), ip.admin_responsibility],
            [Paragraph('Date of Original Appointment', styleB), ip.joining_date],
            ]
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ]    
    elements.append(make_table(data, widths=[6 * cm, 20 * cm], style=ts))    
    # elements.append(PageBreak())
    
    # Education 
    ieds = i.instructoreducation_set.all().order_by('-year')
    data = [[Paragraph('Degrees', styleB),
             Paragraph('Degree', styleB),
             Paragraph('Field', styleB),
             Paragraph('Institution', styleB),
             Paragraph('Date', styleB),
            ]]
    for ied in ieds: 
        data.append(['',
             Paragraph(ied.degree, styleN),
             Paragraph(ied.field, styleN),
             Paragraph(ied.university, styleN),
             Paragraph(ied.year, styleN),
            ])
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 4.5 * cm, 4.5 * cm, 7 * cm, 4 * cm], style=ts))    
    
     
    # events 
    ievs = i.instructoreventparticpation_set.all().order_by('-start_date')
    counter = 1
    cat_header = Paragraph('Conferences, workshops, and professional development programs participated during the past five years', styleB)
    data = []
    for iev in ievs: 
        iev_string = str(counter) + '. ' + iev.title + '. Role: ' + iev.role + ' (' + str(iev.duration) + ' at ' + str(iev.venue) + ')'  
        data.append([cat_header,
             Paragraph(iev_string, styleN),
             Paragraph(str(iev.start_date.year), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))    
    
    # Consultancies 
    icons = i.instructorconsultancy_set.all().order_by('-date')
    counter = 1
    cat_header = Paragraph('Consulting activities during the last five years', styleB)
    data = []
    for icon in icons: 
        icon_string = str(counter) + '. <b>' + icon.organization + '</b>. ' + icon.description   
        data.append([cat_header,
             Paragraph(icon_string, styleN),
             Paragraph(str(icon.date.year), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))
    
    
    # Publications 
    ipbs = i.instructorpublication_set.all().order_by('-id')
    counter = 1
    cat_header = Paragraph('Principal publications during the last five years (give in standard bibliogrpahic format)', styleB)
    data = []
    for ipb in ipbs: 
        pub_string = str(counter) + '. ' + str(ipb)
        data.append([cat_header,
             Paragraph(pub_string, styleN),
             Paragraph('date', styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts)) 

    # Other activities 
    ioas = i.instructorotheractivity_set.all().order_by('-date')
    counter = 1
    cat_header = Paragraph('Other scholarly activities during the last five years (grants, sabbaticals, software development, etc.)', styleB)
    data = []
    for ioa in ioas: 
        pub_string = str(counter) + '. ' + str(ioa.title) + '. ' + str(ioa.description)
        data.append([cat_header,
             Paragraph(pub_string, styleN),
             Paragraph(str(ioa.date), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts)) 
    
    # courses during last two years 
    ics = i.course_set.all().order_by('-year')
    data = [[Paragraph('Courses taught during this and last academic year', styleB),
             Paragraph('Year', styleB),
             Paragraph('Semester', styleB),
             Paragraph('Course Code', styleB),
             Paragraph('Course Title', styleB),
            ]]
    for ic in ics: 
        data.append(['',
                     str(ic.year),
                     str(ic.semester),
                     str(ic.course_code),
                     str(ic.course_name)
                     ])
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[6 * cm, 3 * cm, 3 * cm, 3 * cm, 11 * cm], style=ts)) 


    # Percentage of time given to teaching
    data = [[Paragraph('State percentage of your full-time work dedicated to teaching in the computing program under evaluation', styleB)
             , str(percent_time_teaching) + '%']]
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ]
    elements.append(make_table(data, widths=[6 * cm, 20 * cm], style=ts))

    # END OF REPORT. NOW BUILD 

    doc.build(elements)
    # OUTPUT FILE 
    # doc.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
def report_qec_courselog_pdf(request, course_name, week_range):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefile.pdf"' 
    
    buffer = BytesIO() 
    
    org = Qec()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    doc = FooterDocTemplate(buffer, pagesize=A4)
    frame = org.getFrame(doc)
    
    logo_filename = os.path.join(os.path.dirname(__file__), 'images', get_config('logo_filename'))

    template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer())
    doc.addPageTemplates([template])
    
    # Our main content holder 
    
    elements = []
    
    # title page 
    # SYMBOLS FOR CHECKED/UNCHECKED: \u2713 \u26aa  or x 
    inst_name = Paragraph(get_config('inst_name'), styleH)
    dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB)
    report_title = Paragraph('Weekly Progress Report (Performa 11)', styleB)
    semester = Paragraph("(" + str(course_name.semester) + " " + str(course_name.year) + ")", styleB)
    logobox = Image(logo_filename, 100, 110)
    
    metainfo = [[logobox, inst_name],
                ['', dept_name],
                ['', report_title],
                ['', semester],
                ]
    metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))]
    t1 = LongTable(metainfo, colWidths=[5 * cm, 14 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)
    
    # doc._draw_header_logo('/home/nam/documents/exps/django-tut/fastnu-csd-audit/csdexec/cscm/views/images/fastlogo.png', 10, 10)
    
    elements.append(Spacer(1, 0.5 * cm))
    
    course_name_label = Paragraph(course_name.course_name, styleB)
    inst_name_label = Paragraph(str(course_name.instructor), styleB)
    from_week_label = Paragraph(str(week_range[0]), styleB)
    to_week_label = Paragraph(str(week_range[1]), styleB)
    metainfo = [['Course Name', course_name_label,
                 'Instructor', inst_name_label],
                ['From Week', from_week_label,
                 'To Week', to_week_label],
                ]
    metainfo_tablestyle = []
    t1 = LongTable(metainfo, colWidths=[3 * cm, 6 * cm, 3 * cm, 6 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)
    
    elements.append(Spacer(1, 0.5 * cm))
    
    # elements.append(PageBreak())

    
    # =================== TABLE DATA 
    datas = []
    headLNo = Paragraph('Lec.', styleB)
    headWNo = Paragraph('Wk.', styleB)
    headDate = Paragraph('Date', styleB)
    headDuration = Paragraph('Duration', styleB)
    headTopics = Paragraph('Topics Covered', styleB)
    headEval = Paragraph('Evaluation Instruments Used', styleB)
    headRead = Paragraph('Reading Materials', styleB)
    headSign = Paragraph('Signature', styleB)
    emptypara = Paragraph(' ', styleN)
    
    datas = [[headLNo, headWNo, headDate, headDuration, headTopics, headEval, headRead]]
    
    # courselogentry_data = CourseLogEntry.objects.all()
    courselogentry_data = course_name.courselogentry_set.all().order_by('lecture_date')
    
    start_week = int(week_range[0])
    end_week = int(week_range[1])
    num_assignments = 0 
    num_quizzes = 0 
    gross_contents_covered = ''
    all_contents_covered = True 
    
    l_no = 1 # start
    w_no = 1
    starting_week_of_year = 0
    other_activities = []    
    for i in courselogentry_data:
        l_no = i.lecture_no() 
        w_no = i.week_no() 
         
        if w_no < start_week or w_no > end_week:
            continue 
        
        # entered_logs += 1
        l_date = Paragraph(str(i.lecture_date.strftime("%d-%m, %Y")), styleSmaller)
        l_duration = Paragraph(str(i.duration), styleSmaller)
        l_topics_covered = Paragraph(clean_string(i.topics_covered), styleSmaller)
        l_eval = Paragraph(clean_string(i.evaluation_instruments), styleSmaller)
        l_reading = Paragraph(clean_string(i.reading_materials), styleSmaller)
        emptypara = Paragraph(str(l_no) + ' ' + str(w_no), styleSmaller)
        datas.append([str(l_no), str(w_no), l_date, l_duration, l_topics_covered, l_eval, l_reading])
        
        # logic for calculating meta data 
        num_assignments += i.evaluation_instruments.lower().count('assignment')
        num_quizzes += i.evaluation_instruments.lower().count('quiz')
        gross_contents_covered += i.contents_covered.strip() + '\n'
        if i.contents_covered.strip() != '': 
            all_contents_covered = False
            
        other_activities.append(i.other_activities)
    
        
    if len(datas) < 2: # 2 because we do have a header in any case  
        raise Exception("No Course Log Entries found!") 
        
        
    t = LongTable(datas, colWidths=[1 * cm, 1 * cm, 1.5 * cm, 2 * cm, 6 * cm, 3 * cm, 3 * cm], repeatRows=1)
    
    t.setStyle(TableStyle(org.getTableStyle()))
    elements.append(t)
    elements.append(Spacer(1, 0.5 * cm))
    
    # lower metadata
    metainfo = [[Paragraph('<b>Number of Assignments</b>', styleN), str(num_assignments)],
                 [Paragraph('<b>Number of Quizzes', styleN), str(num_quizzes)],
                ]
    t1 = LongTable(metainfo, colWidths=[6 * cm, 12 * cm])
    t1.setStyle(TableStyle())
    elements.append(t1)
    elements.append(Spacer(1, 1 * cm))
    
    
    metainfo = [[Paragraph('Other activities (if any)', styleB)]]
    
    for oa in other_activities: 
        metainfo.append([Paragraph(str(oa), styleN)])
        
    t1 = LongTable(metainfo, colWidths=[18 * cm])
    t1.setStyle(TableStyle())
    elements.append(t1)
    elements.append(Spacer(1, 0.5 * cm))
        
    
    # elements.append(Spacer(1, 0.5 * cm))
    if all_contents_covered:
         is_covered_yes = '\u2713'
         is_covered_no = 'x'
    else: 
         is_covered_yes = 'x'
         is_covered_no = '\u2713'
    gross_contents_covered = 'NA' if all_contents_covered == '' else gross_contents_covered 
    metainfo = [ [is_covered_yes, 'All contents planned for this period were covered.'],
                 [is_covered_no, 'Some contens planned for this period were not covered. Details below:'],
                 ['', ''],
                 [Paragraph(clean_string(gross_contents_covered), styleN), '']
                ]
    metainfo_tablestyle = [('SPAN', (0, 2), (1, 2)),
                           ('BOX', (0, 3), (1, 3), 0.25, colors.black),
                           ('BOX', (0, 0), (0, 0), 0.25, colors.black),
                           ('BOX', (0, 1), (0, 1), 0.25, colors.black)]
    t1 = LongTable(metainfo, colWidths=[0.6 * cm, 16 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)    
    
    # signature area 
    elements.append(Spacer(1, 1 * cm))
    metainfo = [ [Paragraph('Date', styleB), datetime.datetime.now().strftime('%d-%B-%Y'),
                 Paragraph('Signature', styleB), '', ''],
                ]
    metainfo_tablestyle = [('LINEBELOW', (3, 0), (3, 0), 0.25, colors.black)]
    t1 = LongTable(metainfo, colWidths=[2 * cm, 4 * cm, 2 * cm , 4 * cm, 5 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)    
    
    
    # finalize document 
    doc.build(elements)
    
    
    # OUTPUT FILE 
    # doc.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
def report_nceac_faculty_profile_pdf(request, instructor):
    def make_table(data, widths, style=[]):
        table = LongTable(data, colWidths=widths)
        table.setStyle(TableStyle(style))
        return table

    response = HttpResponse(mimetype="application/pdf")

    buffer = BytesIO()

    org = Nceac()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    styleBC = copy.copy(styleB)
    styleBC.alignment = TA_CENTER

    width, height = A4
    doc = FooterDocTemplate(buffer, pagesize=(height, width))

    frame = org.getFrame(doc)
    template = PageTemplate(
        id="test", frames=frame, onPage=org.get_header_footer(doccode="NCEAC.DOC.008", pagesize=(height, width))
    )
    doc.addPageTemplates([template])

    # Our main content holder

    elements = []

    i = instructor
    ip = i.instructorprofile
    percent_time_teaching = ip.percent_time_teaching

    # title page
    data = [
        [Paragraph("Name", styleB), i.name],
        [Paragraph("Academic Rank", styleB), ip.designation],
        [Paragraph("Administrative Responsibility", styleB), ip.admin_responsibility],
        [Paragraph("Date of Original Appointment", styleB), ip.joining_date],
    ]
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]
    elements.append(make_table(data, widths=[6 * cm, 20 * cm], style=ts))
    # elements.append(PageBreak())

    # Education
    ieds = i.instructoreducation_set.all().order_by("-year")
    data = [
        [
            Paragraph("Degrees", styleB),
            Paragraph("Degree", styleB),
            Paragraph("Field", styleB),
            Paragraph("Institution", styleB),
            Paragraph("Date", styleB),
        ]
    ]
    for ied in ieds:
        data.append(
            [
                "",
                Paragraph(ied.degree, styleN),
                Paragraph(ied.field, styleN),
                Paragraph(ied.university, styleN),
                Paragraph(ied.year, styleN),
            ]
        )
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("SPAN", (0, 0), (0, -1)),
    ]
    elements.append(make_table(data, widths=[6 * cm, 4.5 * cm, 4.5 * cm, 7 * cm, 4 * cm], style=ts))

    # events
    ievs = i.instructoreventparticpation_set.all().order_by("-start_date")
    counter = 1
    cat_header = Paragraph(
        "Conferences, workshops, and professional development programs participated during the past five years", styleB
    )
    data = []
    for iev in ievs:
        iev_string = (
            str(counter)
            + ". "
            + iev.title
            + ". Role: "
            + iev.role
            + " ("
            + str(iev.duration)
            + " at "
            + str(iev.venue)
            + ")"
        )
        data.append([cat_header, Paragraph(iev_string, styleN), Paragraph(str(iev.start_date.year), styleN)])
        cat_header = ""
        counter += 1
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("SPAN", (0, 0), (0, -1)),
    ]
    if len(data) < 1:
        data.append([cat_header, "None", "-"])
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))

    # Consultancies
    icons = i.instructorconsultancy_set.all().order_by("-date")
    counter = 1
    cat_header = Paragraph("Consulting activities during the last five years", styleB)
    data = []
    for icon in icons:
        icon_string = str(counter) + ". <b>" + icon.organization + "</b>. " + icon.description
        data.append([cat_header, Paragraph(icon_string, styleN), Paragraph(str(icon.date.year), styleN)])
        cat_header = ""
        counter += 1
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("SPAN", (0, 0), (0, -1)),
    ]
    if len(data) < 1:
        data.append([cat_header, "None", "-"])
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))

    # Publications
    ipbs = i.instructorpublication_set.all().order_by("-pub_date")
    counter = 1
    cat_header = Paragraph(
        "Principal publications during the last five years (give in standard bibliogrpahic format)", styleB
    )
    data = []
    for ipb in ipbs:
        pub_string = str(counter) + ". " + ipb.get_citation()
        data.append([cat_header, Paragraph(pub_string, styleN), Paragraph(str(ipb.pub_date.year), styleN)])
        cat_header = ""
        counter = counter + 1

    ts = [
        ("INNERGRID", (1, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (0, -1), 0.25, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        # ('SPAN', (0, 0), (0, -1)) # gives error for some reason
    ]
    if len(data) < 1:
        data.append([cat_header, "None", "-"])
    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))

    # Other activities
    ioas = i.instructorotheractivity_set.all().order_by("-date")
    counter = 1
    cat_header = Paragraph(
        "Other scholarly activities during the last five years (grants, sabbaticals, software development, etc.)",
        styleB,
    )
    data = []
    for ioa in ioas:
        pub_string = str(counter) + ". " + str(ioa.title) + ". " + str(ioa.description)
        data.append([cat_header, Paragraph(pub_string, styleN), Paragraph(str(ioa.date), styleN)])
        cat_header = ""
        counter += 1
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("SPAN", (0, 0), (0, -1)),
    ]
    if len(data) < 1:
        data.append([cat_header, "None", "-"])

    elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts))

    # courses during last two years
    ics = i.course_set.all().order_by("-year")
    data = [
        [
            Paragraph("Courses taught during this and last academic year", styleB),
            Paragraph("Year", styleB),
            Paragraph("Semester", styleB),
            Paragraph("Course Code", styleB),
            Paragraph("Course Title", styleB),
        ]
    ]
    for ic in ics:
        data.append(["", str(ic.year), str(ic.semester), str(ic.course_code), str(ic.course_name)])
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        # ('SPAN', (0, 0), (0, -1))
    ]
    elements.append(make_table(data, widths=[6 * cm, 3 * cm, 3 * cm, 3 * cm, 11 * cm], style=ts))

    # Percentage of time given to teaching
    data = [
        [
            Paragraph(
                "State percentage of your full-time work dedicated to teaching in the computing program under evaluation",
                styleB,
            ),
            str(percent_time_teaching) + "%",
        ]
    ]
    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.15, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]
    elements.append(make_table(data, widths=[6 * cm, 20 * cm], style=ts))

    # END OF REPORT. NOW BUILD

    doc.build(elements)
    # OUTPUT FILE
    # doc.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
def report_qec_faculty_profile_pdf(request, instructor):
    def make_table(data, widths, style=[]):
        table = LongTable(data, colWidths=widths)
        table.setStyle(TableStyle(style))
        return table 
        
    response = HttpResponse(mimetype='application/pdf')
    
    buffer = BytesIO() 
    
    org = Qec()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    styleBC = copy.copy(styleB)
    styleBC.alignment = TA_CENTER 
    
    width, height = A4
    doc = FooterDocTemplate(buffer, pagesize=A4)
    
    frame = org.getFrame(doc)
    template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer(doccode="Proforma 9"))
    doc.addPageTemplates([template])
    
    # Our main content holder 
    
    logo_filename = os.path.join(os.path.dirname(__file__), '../../cscm/views/images', get_config('logo_filename'))


    elements = []
    
    inst_name = Paragraph(get_config('inst_name'), styleH)
    dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB)
    report_title = Paragraph('Proforma 9: Faculty CV', styleB)
    logobox = Image(logo_filename, 75, 80)
    
    metainfo = [[logobox, inst_name],
                ['', dept_name],
                ['', report_title],
                ]
    
    metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))]
    t1 = LongTable(metainfo, colWidths=[3 * cm, 15 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)
    elements.append(Spacer(1, 0.5 * cm))
    
    i = instructor 
    ip = i.instructorprofile
    percent_time_teaching = ip.percent_time_teaching
    
    # title page 
    data = [[Paragraph('Name', styleB), i.name],
            [Paragraph('Academic Rank', styleB), ip.designation],
            [Paragraph('Administrative Responsibility', styleB), Paragraph(ip.admin_responsibility.replace('\n', '<br />'), styleN)],
            [Paragraph('Date of Original Appointment', styleB), ip.joining_date],
            [Paragraph('Email', styleB), ip.email],
            [Paragraph('Address', styleB), Paragraph(clean_string(ip.contact_address), styleN)],
            [Paragraph('Contact Number', styleB), ip.contact_number],
            ]
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ]    
    elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts))    
    # elements.append(PageBreak())
    
    # Education 
    ieds = i.instructoreducation_set.all().order_by('-year')
    data = [[Paragraph('Education', styleB),
             Paragraph('Degree', styleB),
             Paragraph('Field', styleB),
             Paragraph('Institution', styleB),
             Paragraph('Date', styleB),
            ]]
    for ied in ieds: 
        data.append(['',
             Paragraph(ied.degree, styleN),
             Paragraph(ied.field, styleN),
             Paragraph(ied.university, styleN),
             Paragraph(ied.year, styleN),
            ])
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[5 * cm, 2.5 * cm, 3 * cm, 5 * cm, 1.5 * cm], style=ts))    
    
    # events 
    ievs = i.instructoreventparticpation_set.all().order_by('-start_date')
    counter = 1
    cat_header = Paragraph('Conferences, workshops, and professional development programs participated during the past five years', styleB)
    data = []
    for iev in ievs: 
        iev_string = str(counter) + '. ' + iev.title + '. Role: ' + iev.role + ' (' + str(iev.duration) + ' at ' + str(iev.venue) + ')'  
        data.append([cat_header,
             Paragraph(iev_string, styleN),
             Paragraph(str(iev.start_date.year), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    if len(data) < 1: 
        data.append([cat_header, 'None' , '-'])
    elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts))    
    
    
    # Consultancies 
    icons = i.instructorconsultancy_set.all().order_by('-date')
    counter = 1
    cat_header = Paragraph('Consulting activities during the last five years', styleB)
    data = []
    for icon in icons: 
        icon_string = str(counter) + '. <b>' + icon.organization + '</b>. ' + icon.description   
        data.append([cat_header,
             Paragraph(icon_string, styleN),
             Paragraph(str(icon.date.year), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    if len(data) < 1: 
        data.append([cat_header, 'None' , '-'])
    elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts))
    
    # research interest
    data = [[Paragraph('Research Statement', styleB), Paragraph(clean_string(ip.statement_of_research), styleN)],
            ]
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ]    
    elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts))    
    
    # Publications 
    ipbs = i.instructorpublication_set.all().order_by('-pub_date')
    counter = 1
    cat_header = Paragraph('Principal publications during the last five years (give in standard bibliogrpahic format)', styleB)
    data = []
    for ipb in ipbs: 
        pub_string = str(counter) + '. ' + ipb.get_citation()
        data.append([cat_header,
             Paragraph(pub_string, styleN),
             Paragraph(str(ipb.pub_date.year), styleN),
            ])
        cat_header = ''
        counter = counter + 1
        
    ts = [  ('INNERGRID', (1, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (0, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            # ('SPAN', (0, 0), (0, -1)) # gives error for some reason 
            ]    
    if len(data) < 1: 
        data.append([cat_header, 'None' , '-'])
    elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) 

    # Other activities 
    ioas = i.instructorotheractivity_set.all().order_by('-date')
    counter = 1
    cat_header = Paragraph('Other scholarly activities during the last five years (grants, sabbaticals, software development, etc.)', styleB)
    data = []
    for ioa in ioas: 
        pub_string = str(counter) + '. ' + str(ioa.title) + '. ' + str(ioa.description)
        data.append([cat_header,
             Paragraph(pub_string, styleN),
             Paragraph(str(ioa.date), styleN),
            ])
        cat_header = ''
        counter += 1
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (0, 0), (0, -1))
            ]    
    if len(data) < 1: 
        data.append([cat_header, 'None' , '-'])
        
    elements.append(make_table(data, widths=[5 * cm, 10.5 * cm, 1.5 * cm], style=ts)) 
    
    # courses during last two years 
    ics = i.course_set.all().order_by('-year')
    data = [[Paragraph('Courses taught during this and last academic year', styleB),
             Paragraph('Year', styleB),
             Paragraph('Semester', styleB),
             Paragraph('Course Code', styleB),
             Paragraph('Course Title', styleB),
            ]]
    for ic in ics: 
        data.append(['',
                     str(ic.year),
                     str(ic.semester),
                     str(ic.course_code),
                     Paragraph(str(ic.course_name), styleN)
                     ])
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            # ('SPAN', (0, 0), (0, -1))
            ]    
    elements.append(make_table(data, widths=[5 * cm, 1.5 * cm, 2 * cm, 2 * cm, 6.5 * cm], style=ts)) 


    # Services to dept
    data = [[Paragraph('Services to the University', styleB), Paragraph(clean_string(ip.services_to_dept), styleN)],
            ]
    ts = [  ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ]    
    elements.append(make_table(data, widths=[5 * cm, 12 * cm], style=ts))    

    # END OF REPORT. NOW BUILD 

    doc.build(elements)
    # OUTPUT FILE 
    # doc.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
def report_internal_courseoutline_pdf(request, course_name):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefile.pdf"' 
    
    buffer = BytesIO() 
    
    org = Internal()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    doc = FooterDocTemplate(buffer, pagesize=A4)
    frame = org.getFrame(doc)
    template = PageTemplate(id='test', frames=frame, onPage=org.get_header_footer(doccode="", pagesize=A4))
    doc.addPageTemplates([template])
    width, height = A4
    frame_width = width - ((doc.leftMargin - 20) * 2)
    
    logo_filename = os.path.join(os.path.dirname(__file__), 'images', get_config('logo_filename'))


    # Our main content holder 
    
    elements = []

    inst_name = Paragraph(get_config('inst_name'), styleH)
    dept_name = Paragraph(get_config('dept_name') + ", " + get_config('campus_name'), styleB)
    report_title = Paragraph('Course Outline', styleB)
    semester = Paragraph("(" + str(course_name.semester) + " " + str(course_name.year) + ")", styleB)
    logobox = Image(logo_filename, 100, 110)
    
    metainfo = [[logobox, inst_name],
                ['', dept_name],
                ['', report_title],
                ['', semester],
                ]
    metainfo_tablestyle = [('SPAN', (0, 0), (0, -1))]
    t1 = LongTable(metainfo, colWidths=[5 * cm, 14 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)

    
    # title page 
#    inst_name_head = Paragraph('INSTITUTION', styleB)
#    inst_name = Paragraph(get_config('inst_name'), styleN)
#    dept_name_head = Paragraph('PROGRAM(S) TO BE EVALUATED', styleB)
#    dept_name = Paragraph("BS (CS)", styleN)
#    
#    metainfo_tablestyle = [
#                    # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
#                    ('LINEBELOW', (1, 0), (1, -1), 0.25, colors.black),
#                    # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
#                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
#                    ]
#    metainfo = [[inst_name_head, inst_name], [dept_name_head, dept_name]]
#    t1 = LongTable(metainfo, colWidths=[3 * cm, frame_width - (3 * cm)])
#    t1.setStyle(TableStyle(metainfo_tablestyle))
#    elements.append(t1)
    
    elements.append(Spacer(1, 0.5 * cm))
#    elements.append(Paragraph('A. COURSE DESCRIPTION', styleH))
#    elements.append(Paragraph('(Fill out the following table for each course in your computer science curriculum. A filled out form should not be more than 2-3 pages.', styleN))
#    elements.append(Spacer(1, 0.5 * cm))


    # =================== TABLE DATA 
    c = course_name 
    try:
        co = CourseOutline.objects.filter(course=c)[0] # one-to-one relation
    except Exception, err:
        raise RuntimeError("Course outlines not defined for " + str(course_name)) 
def report_nceac_courselog_pdf(request, course_name):
    response = HttpResponse(mimetype="application/pdf")
    response["Content-Disposition"] = 'attachment; filename="somefile.pdf"'

    buffer = BytesIO()

    org = Nceac()
    styleN, styleB, styleH, styleSmaller = org.getTextStyles()
    styleBC = copy.copy(styleB)
    styleBC.alignment = TA_CENTER

    doc = FooterDocTemplate(buffer, pagesize=A4)
    frame = org.getFrame(doc)
    template = PageTemplate(id="test", frames=frame, onPage=org.get_header_footer(doccode="NCEAC.DOC.008"))
    doc.addPageTemplates([template])

    # Our main content holder

    elements = []

    # title page

    metainfo_tablestyle = [("ALIGN", (0, 0), (-1, -1), "CENTER")]
    metainfo = [
        [Paragraph("NCEAC Secretariat", styleBC)],
        [Paragraph("Foundation University Institute of Management & Computer Sciences", styleBC)],
        [Paragraph("New Lalazar, Gulberg Avenue, Rawalpindi Cantt, 46000", styleBC)],
        [Paragraph("Phone : 051- 5516094, Fax: 051-5584574, PABX: 051- 5790360-2 (Ext. 202)", styleBC)],
        [Paragraph("http://www.nceac.org/", styleBC)],
        [Spacer(1 * cm, 1 * cm)],
        [Paragraph("COURSE LOG TEMPLATE", styleBC)],
    ]

    t1 = LongTable(metainfo, colWidths=[20 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)

    elements.append(Spacer(1 * cm, 1 * cm))

    inst_name_head = Paragraph("INSITUTION", styleB)
    inst_name = Paragraph(get_config("inst_name"), styleN)
    dept_name_head = Paragraph("PROGRAM(S) TO BE EVALUATED", styleB)
    dept_name = Paragraph("BS (CS)", styleN)

    metainfo_tablestyle = [
        # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ("LINEBELOW", (1, 0), (1, -1), 0.25, colors.black),
        # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]
    metainfo = [[inst_name_head, inst_name], [dept_name_head, dept_name]]
    t1 = LongTable(metainfo, colWidths=[3 * cm, 12 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)

    elements.append(Spacer(1 * cm, 1 * cm))

    this_course_name_head = Paragraph("Course Name", styleB)
    this_course_name = Paragraph(str(course_name), styleN)
    dept_name_head = Paragraph("Catalog Number", styleB)
    dept_name = Paragraph(str(course_name.course_code), styleN)
    inst_name_head = Paragraph("Instructor Name", styleB)
    inst_name = Paragraph(str(course_name.instructor), styleN)

    metainfo_tablestyle = [
        # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ("LINEBELOW", (1, 0), (1, -1), 0.25, colors.black),
        # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]
    metainfo = [[this_course_name_head, this_course_name], [dept_name_head, dept_name], [inst_name_head, inst_name]]
    t1 = LongTable(metainfo, colWidths=[3 * cm, 12 * cm])
    t1.setStyle(TableStyle(metainfo_tablestyle))
    elements.append(t1)

    elements.append(PageBreak())

    # =================== TABLE DATA
    datas = []
    headDate = Paragraph("Date", styleB)
    headDuration = Paragraph("Duration", styleB)
    headTopics = Paragraph("Topics Covered", styleB)
    headEval = Paragraph("Evaluation Instruments Used", styleB)
    headSign = Paragraph("Signature", styleB)
    emptypara = Paragraph(" ", styleN)

    datas = [[headDate, headDuration, headTopics, headEval, headSign]]

    # courselogentry_data = CourseLogEntry.objects.all()
    courselogentry_data = course_name.courselogentry_set.all()

    # for x in range(1, 50):
    #    datas.append(
    #        [x, x + 1, x + 2, x + 4, x + 5]
    #    )
    for i in courselogentry_data:
        # entered_logs += 1
        l_date = Paragraph(str(i.lecture_date.strftime("%d-%m, %Y")), styleSmaller)
        l_duration = Paragraph(str(i.duration), styleSmaller)
        l_topics_covered = Paragraph(clean_string(i.topics_covered), styleSmaller)
        l_eval = Paragraph(clean_string(i.evaluation_instruments), styleSmaller)

        datas.append([l_date, l_duration, l_topics_covered, l_eval, emptypara])

    # for i in range(entered_logs, 16):
    #    data.append([[emptypara, emptypara, emptypara, emptypara, emptypara]])

    t = LongTable(datas, colWidths=[1.5 * cm, 2 * cm, 8 * cm, 3 * cm, 3 * cm], repeatRows=1)

    t.setStyle(TableStyle(org.getTableStyle()))
    elements.append(t)
    doc.build(elements)

    # OUTPUT FILE
    # doc.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response