コード例 #1
0
def merge_report_bhf(subj_id, report_filepath, graphs_dir):
    ps = ParagraphStyle(
        name='Normal',
        fontName='Helvetica',
        fontSize=10,
        spaceAfter=8,
    )

    doc = SimpleDocTemplate(graphs_dir + "{}_graphs.pdf".format(subj_id), rightMargin=50,
                            leftMargin=50, topMargin=50, bottomMargin=50)
    parts = []

    image = get_image(graphs_dir + "{}_mean_exposure.png".format(subj_id), width=480)
    parts.append(image)

    parts.append(Spacer(width=0, height=35))
    lines = tuple(open(graphs_dir + "{}_stats.txt".format(subj_id), 'r'))
    for line in lines:
        parts.append(Paragraph(line, ps))

    parts.append(PageBreak())

    image = get_image(graphs_dir + "{}_airspeck_map.png".format(subj_id), width=480)
    parts.append(image)

    parts.append(Spacer(width=0, height=20))

    image = get_image(graphs_dir + "viridis_legend.png".format(subj_id), width=300) #was 220
    parts.append(image)
    
    parts.append(PageBreak())
    
    image = get_image(graphs_dir + "{}_airspeck_map1.png".format(subj_id), width=480)
    parts.append(image)
    
    image = get_image(graphs_dir + "{}_airspeck_map2.png".format(subj_id), width=480)
    parts.append(image)
    
    parts.append(PageBreak())
    
    image = get_image(graphs_dir + "{}_airspeck_map3.png".format(subj_id), width=480)
    parts.append(image)
    
    image = get_image(graphs_dir + "{}_airspeck_map4.png".format(subj_id), width=480)
    parts.append(image)

    #parts.append(PageBreak())

    #image = get_image(graphs_dir + "{}_detailed_exposure.png".format(subj_id), rotated=True, width=720)
    #image_2 = get_image(graphs_dir + "{}_detailed_exposure.png".format(subj_id), rotated=True, width=720)

    #parts.append(image_2)

    doc.build(parts)

    output = PdfFileWriter()

    with open(bhf_reports_dir + "first_page.pdf", "rb") as f:
        cover_pdf = PdfFileReader(f)
        output.addPage(cover_pdf.getPage(0))

        with open(graphs_dir + "{}_graphs.pdf".format(subj_id), "rb") as f:
            rest_pdf = PdfFileReader(f)
            for p_idx in range(rest_pdf.getNumPages()):
                output.addPage(rest_pdf.getPage(p_idx))

            with open(report_filepath, "wb") as f:
                output.write(f)
コード例 #2
0
def tickets(request, performance_uuid, format):

    # Get performance and venue
    performance = get_object_or_404(ShowPerformance, uuid = performance_uuid)
    assert performance.has_open_checkpoint
    assert format == 'html' or format == 'pdf'
    venue = performance.show.venue

    # Get tickets
    venue_tickets = performance.tickets.filter(sale__completed__isnull = False, sale__venue = venue, refund__isnull = True).order_by('id')
    non_venue_tickets = performance.tickets.filter(sale__completed__isnull = False, sale__venue__isnull = True, refund__isnull = True).order_by('id')
    cancelled_tickets = performance.tickets.filter(refund__isnull = False).order_by('id')

    # Check for HTML
    if format == 'html':

        # Render tickets
        context = {
            'venue': venue,
            'performance': performance,
            'venue_tickets': venue_tickets,
            'non_venue_tickets': non_venue_tickets,
            'cancelled_tickets': cancelled_tickets,
        }
        return render(request, "venue/_main_tickets.html", context)

    # Render as PDF
    response = HttpResponse(content_type = 'application/pdf')
    response['Content-Disposition'] = 'inline'
    doc = SimpleDocTemplate(
        response,
        pagesize = portrait(A4),
        leftMargin = 2.5*cm,
        rightMargin = 2.5*cm,
        topMargin = 2.5*cm,
        bottomMargin = 2.5*cm,
    )
    styles = getSampleStyleSheet()
    story = []

    # Festival banner
    if request.festival.banner:
        banner = Image(request.festival.banner.get_absolute_path(), width = 16*cm, height = 4*cm)
        banner.hAlign = 'CENTER'
        story.append(banner)
        story.append(Spacer(1, 1*cm))

    # Venue and performance
    table = Table(
        (
            (Paragraph('<para><b>Venue:</b></para>', styles['Normal']), venue.name),
            (Paragraph('<para><b>Show:</b></para>', styles['Normal']), performance.show.name),
            (Paragraph('<para><b>Performance:</b></para>', styles['Normal']), f"{performance.date:%A, %d %B} at {performance.time:%I:%M%p}"),
        ),
        colWidths = (4*cm, 12*cm),
        hAlign = 'LEFT'
    )
    story.append(table)

    # Box Offixe and Online tickets
    story.append(Paragraph('<para>Box Office and Online Sales</para>', styles['Heading3']))
    table_data = []
    table_data.append((
        Paragraph(f"<para><b>Ticket No</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Name/e-mail</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Type</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Sale</b></para>", styles['Normal']),
    ))
    for ticket in non_venue_tickets:
        name_email= ticket.user.email if ticket.user else ticket.sale.customer
        sale_type = 'Venue' if ticket.sale.user else 'Box office' if ticket.sale.boxoffice else 'Online'
        table_data.append((
            str(ticket.id),
            name_email,
            ticket.description,
            sale_type,
        ))
    table = Table(
        table_data,
        colWidths = (2.5*cm, 8.5*cm, 2.5*cm, 2.5*cm),
        hAlign = 'LEFT',
    )
    story.append(table)

    # Venue tickets
    story.append(Paragraph('<para>Venue Sales</para>', styles['Heading3']))
    table_data = []
    table_data.append((
        Paragraph(f"<para><b>Ticket No</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Name/e-mail</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Type</b></para>", styles['Normal']),
        Paragraph(f"<para><b>Sale</b></para>", styles['Normal']),
    ))
    for ticket in venue_tickets:
        name_email= ticket.user.email if ticket.user else ticket.sale.customer
        sale_type = 'Venue' if ticket.sale.user else 'Box office' if ticket.sale.boxoffice else 'Online'
        table_data.append((
            str(ticket.id),
            name_email,
            ticket.description,
            sale_type,
        ))
    table = Table(
        table_data,
        colWidths = (2.5*cm, 8.5*cm, 2.5*cm, 2.5*cm),
        hAlign = 'LEFT',
    )
    story.append(table)

    # Cancelled tickets
    if cancelled_tickets:
        story.append(Paragraph('<para>Cancelled Tickets</para>', styles['Heading3']))
        table_data = []
        table_data.append((
            Paragraph(f"<para><b>Ticket No</b></para>", styles['Normal']),
            Paragraph(f"<para><b>Name/e-mail</b></para>", styles['Normal']),
            Paragraph(f"<para><b>Type</b></para>", styles['Normal']),
            Paragraph(f"<para><b>Sale</b></para>", styles['Normal']),
        ))
        for ticket in cancelled_tickets:
            name_email= ticket.user.email if ticket.user else ticket.sale.customer
            sale_type = 'Venue' if ticket.sale.user else 'Box office' if ticket.sale.boxoffice else 'Online'
            table_data.append((
                str(ticket.id),
                name_email,
                ticket.description,
                sale_type,
            ))
        table = Table(
            table_data,
            colWidths = (2.5*cm, 8.5*cm, 2.5*cm, 2.5*cm),
            hAlign = 'LEFT',
        )
        story.append(table)

    # Render PDF document and return it
    doc.build(story)
    return response
コード例 #3
0
    def drawPlots(self):
        
        P = Paragraph('The following ips were found on the {} log file'.format(self.DATA_TYPE),  styles['Normal_CENTER'])
        self.flowables.append(P)
        self.flowables.append(Spacer(20, 1*inch))
        
        
        data = []
        values = ()
        names = []
        new_data = []

        renormalized = {}

        for l in self.NORMALIZED_DATA:
            new_data.append(self.NORMALIZED_DATA[l]['location'])
        new_data = list(set(new_data))

        for loc in new_data:
            for t in self.NORMALIZED_DATA:
                if self.NORMALIZED_DATA[t]['location'] == loc:
                    if loc in renormalized:
                        renormalized[loc] += int(self.NORMALIZED_DATA[t]['attempts'])
                    else: 
                        renormalized[loc] = int(self.NORMALIZED_DATA[t]['attempts'])

        for line in renormalized:
            values += (renormalized[line],)
            names.append(line)
        data.append(values)

        print(max(values))

        
        spacing = 0
        height = 0
        width = 0
        step = 0
        maxvalue = 0
        if max(values) > 1000:
            spacing = 0
            height = 500
            step = 150
            maxvalue = max(values)
        elif max(values) < 1000 and max(values) > 500:
            spacing = 0
            height = 400
            step = 100
            maxvalue = 1000
        elif max(values) < 500 and max(values) > 250:
            spacing = 0
            height = 300
            step = 50
            maxvalue = 500
        elif max(values) < 250 and max(values) > 100:
            spacing = 0
            height = 200
            step = 25
            maxvalue = 250
        elif max(values) < 100 and max(values) > 50:
            spacing = 0
            height = 100
            step = 10
            maxvalue = 100
        elif max(values) < 50 and max(values) > 10:
            spacing = 0
            height = 50
            step = 5
            maxvalue = 50
        elif max(values) < 10:
            spacing = 0
            height = 25
            step = 1
            maxvalue = 10

        drawing = Drawing(400, height)

        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 0
        bc.height = height
        bc.width = 400
        bc.data = data
        bc.strokeColor = colors.white
        bc.valueAxis.valueMin = spacing
        bc.valueAxis.valueMax = maxvalue
        bc.valueAxis.valueStep = step
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = -5
        bc.categoryAxis.labels.angle = 90
        bc.categoryAxis.labels.fontName = 'Helvetica'
        bc.categoryAxis.categoryNames = names

        drawing.add(bc)
        self.flowables.append(drawing)
        self.flowables.append(Spacer(20, 1*inch))
        
                
コード例 #4
0
def _create_approval(approval_buffer, approval, proposal, copied_to_permit, user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame], onPage=_create_approval_header)

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

    # this is the only way to get data into the onPage callback function
    doc.approval = approval
    doc.site_url = site_url
    region = approval.region if hasattr(approval, 'region') else ''
    district = approval.district if hasattr(approval, 'district') else ''
    region_district = '{} - {}'.format(region, district) if district else region

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []


    title = approval.title.encode('UTF-8') if approval.title else ''

    #Organization details

    address = proposal.applicant_address
    # address = proposal.applicant_address
    if proposal.org_applicant:
        email = proposal.org_applicant.organisation.organisation_set.all().first().contacts.all().first().email
    else:
        email= proposal.submitter.email
    elements.append(Paragraph(email,styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph(_format_name(approval.applicant),styles['BoldLeft']))
    elements.append(Paragraph(address.line1, styles['BoldLeft']))
    elements.append(Paragraph(address.line2, styles['BoldLeft']))
    elements.append(Paragraph(address.line3, styles['BoldLeft']))
    # if proposal.org_applicant:
    #     elements.append(Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['BoldLeft']))
    # else:
    #     elements.append(Paragraph('%s %s' % (address.state, address.postcode), styles['BoldLeft']))
    elements.append(Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['BoldLeft']))
    elements.append(Paragraph(address.country.name, styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    #elements.append(Paragraph(approval.activity, styles['InfoTitleLargeLeft']))
    elements.append(Paragraph('APPROVAL OF PROPOSAL {} {} TO UNDERTAKE Commercial Operator Licensing ACTIVITY IN {}'.format(title, proposal.lodgement_number, region_district), styles['InfoTitleLargeLeft']))
    #elements.append(Paragraph(approval.tenure if hasattr(approval, 'tenure') else '', styles['InfoTitleLargeRight']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('The submitted proposal {} {} has been assessed and approved. The approval is granted on the understanding that: '.format(title, proposal.lodgement_number), styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    list_of_bullets= []
    list_of_bullets.append('The potential impacts of the proposal on values the department manages have been removed or minimised to a level \'As Low As Reasonably Practicable\' (ALARP) and the proposal is consistent with departmental objectives, associated management plans and the land use category/s in the activity area.')
    list_of_bullets.append('Approval is granted for the period {} to {}.  This approval is not valid if {} makes changes to what has been proposed or the proposal has expired.  To change the proposal or seek an extension, the proponent must re-submit the proposal for assessment.'.format(approval.start_date.strftime(DATE_FORMAT), approval.expiry_date.strftime(DATE_FORMAT),_format_name(approval.applicant)))
    list_of_bullets.append('The proponent accepts responsibility for advising {} of new information or unforeseen threats that may affect the risk of the proposed activity.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('Information provided by {0} for the purposes of this proposal will not be provided to third parties without permission from {0}.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('The proponent accepts responsibility for supervising and monitoring implementation of activity/ies to ensure compliance with this proposal. {} reserves the right to request documents and records demonstrating compliance for departmental monitoring and auditing.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('Non-compliance with the conditions of the proposal may trigger a suspension or withdrawal of the approval for this activity.')
    list_of_bullets.append('Management actions listed in Appendix 1 are implemented.')

    understandingList = ListFlowable(
            [ListItem(Paragraph(a, styles['Left']), bulletColour='black', value='circle') for a in list_of_bullets],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=SMALL_FONTSIZE, bulletType='bullet')
            #bulletFontName=BOLD_FONTNAME
    elements.append(understandingList)

    # proposal requirements
    requirements = proposal.requirements.all().exclude(is_deleted=True)
    if requirements.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('The following requirements must be satisfied for the approval of the proposal not to be withdrawn:', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable(
            [Paragraph(a.requirement, styles['Left']) for a in requirements.order_by('order')],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # if copied_to_permit:
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph('Assessor Comments', styles['BoldLeft']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #     for k,v in copied_to_permit:
    #         elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
    #         elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
    #         elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements += _layout_extracted_fields(approval.extracted_fields)

    # additional information
    '''if approval.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))
        elements += _layout_paragraphs(approval.additional_information)'''

    # delegation holds the dates, approvale and issuer details.
    delegation = []

    # dates and licensing officer
    # dates_licensing_officer_table_style = TableStyle([('VALIGN', (0, 0), (-2, -1), 'TOP'),
    #                                                   ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')])

    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # date_headings = [Paragraph('Date of Issue', styles['BoldLeft']), Paragraph('Valid From', styles['BoldLeft']),
    #                  Paragraph('Date of Expiry', styles['BoldLeft'])]
    # date_values = [Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.start_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.expiry_date.strftime(DATE_FORMAT), styles['Left'])]

    # if approval.original_issue_date is not None:
    #     date_headings.insert(0, Paragraph('Original Date of Issue', styles['BoldLeft']))
    #     date_values.insert(0, Paragraph(approval.original_issue_date.strftime(DATE_FORMAT), styles['Left']))

    # delegation.append(Table([[date_headings, date_values]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=dates_licensing_officer_table_style))

    # proponent details
    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # address = proposal.applicant.organisation.postal_address
    # address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
    #                       Paragraph(address.line3, styles['Left']),
    #                       Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
    #                       Paragraph(address.country.name, styles['Left'])]
    # delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
    #                           [Paragraph(_format_name(approval.applicant),
    #                                      styles['Left'])] + address_paragraphs]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=approval_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Should you have any queries about this approval, please contact {} {}, '
                                'on {} or by email at {}'.format(user.first_name, user.last_name, settings.DEP_PHONE, user.email), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('To provide feedback on the system used to submit the approval or update contact details, please '
        'contact {} Works Coordinator - {}'.format(settings.SYSTEM_NAME_SHORT, settings.SUPPORT_EMAIL), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Approved on behalf of the', styles['Left']))
    delegation.append(Paragraph('{}'.format(settings.DEP_NAME), styles['BoldLeft']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    delegation.append(Paragraph('{} {}'.format(user.first_name, user.last_name), styles['Left']))
    delegation.append(Paragraph('{}'.format(region_district), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']))

    elements.append(KeepTogether(delegation))

    # Appendix section
    elements.append(PageBreak())
    elements.append(Paragraph('Appendix 1 - Management Actions', styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    if copied_to_permit:
        # for k,v in copied_to_permit:
        #     elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
        #     elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
        #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        for item in copied_to_permit:
            for key in item:
               elements.append(Paragraph(key.encode('UTF-8'), styles['Left']))
               elements.append(Paragraph(item[key].encode('UTF-8'), styles['Left']))
    else:
        elements.append(Paragraph('There are no management actions.', styles['Left']))


    doc.build(elements)

    return approval_buffer
コード例 #5
0
def _layout_extracted_fields(extracted_fields):
    elements = []

    def __children_have_data(field):
        for group in field.get('children', []):
            for child_field in group:
                if child_field.get('data'):
                    return True

        return False

    # information extracted from application
    if extracted_fields:
        for field in extracted_fields:
            if 'children' not in field:
                if 'data' in field and field['data']:
                    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                    elements.append(Paragraph(field['label'], styles['BoldLeft']))

                    if field['help_text']:
                        elements.append(Paragraph(field['help_text'], styles['ItalicLeft']))

                    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                    if field['type'] in ['text', 'text_area']:
                        elements += _layout_paragraphs(field['data'])
                    elif field['type'] in ['radiobuttons', 'select']:
                        elements.append(Paragraph(dict([i.values() for i in field['options']]).
                                                  get(field['data'], 'Not Specified'), styles['Left']))
                    else:
                        elements.append(Paragraph(field['data'], styles['Left']))

                elif field['type'] == 'label':
                    if any([option.get('data', 'off') == 'on' for option in field['options']]):
                        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                        elements.append(Paragraph(field['label'], styles['BoldLeft']))

                        if field['help_text']:
                            elements.append(Paragraph(field['help_text'], styles['ItalicLeft']))

                        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                        elements.append(Paragraph(', '.join([option['label'] for option in field['options']
                                                            if option.get('data', 'off') == 'on']),
                                        styles['Left']))
            else:
                if not __children_have_data(field):
                    continue

                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                elements.append(Paragraph(field['label'], styles['BoldLeft']))

                if field['help_text']:
                    elements.append(Paragraph(field['help_text'], styles['ItalicLeft']))

                table_data = []
                for index, group in enumerate(field['children']):
                    if index == 0:
                        heading_row = []
                        for child_field in group:
                            heading_row.append(Paragraph(child_field['label'], styles['BoldLeft']))
                        if heading_row:
                            table_data.append(heading_row)

                    row = []
                    for child_field in group:
                        if child_field['type'] in ['radiobuttons', 'select']:
                            row.append(Paragraph(dict([i.values() for i in child_field['options']]).
                                                 get(child_field['data'], 'Not Specified'), styles['Left']))
                        elif child_field['type'] == 'label':
                            if any([option.get('data', 'off') == 'on' for option in child_field['options']]):
                                row.append(Paragraph(', '.join([option['label'] for option in child_field['options']
                                                                if option.get('data', 'off') == 'on']),
                                                     styles['Left']))
                            else:
                                row.append(Paragraph('Not Specified', styles['Left']))
                        else:
                            row.append(Paragraph(child_field['data'], styles['Left']))

                    if row:
                        table_data.append(row)

                if table_data:
                    elements.append(Table(table_data, style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    return elements
コード例 #6
0
    def __init__(self,
                 input_filename,
                 output_filename,
                 title,
                 orient_landscape=False):

        if orient_landscape:
            rightMargin = 62
            leftMargin = 50
            topMargin = 50
            bottomMargin = 50
        else:
            rightMargin = 62
            leftMargin = 50
            topMargin = 50
            bottomMargin = 90

        self.doc = SimpleDocTemplate(
            output_filename,
            pagesize=landscape(A4) if orient_landscape else A4,
            rightMargin=rightMargin,
            leftMargin=leftMargin,
            topMargin=topMargin,
            bottomMargin=bottomMargin)

        self.setup_custom_fonts()

        print(f"Left Margin: {self.leftMargin}")
        print(f"Right Margin: {self.rightMargin}")
        print(f"Top Margin: {self.topMargin}")
        print(f"Bottom Margin: {self.bottomMargin}")
        print(f"Inner Width: {self.inner_width}")
        print(f"Inner Height: {self.inner_height}")
        self.elements = []

        # Create landscape and portrait page templates
        portrait_frame = Frame(self.leftMargin,
                               self.bottomMargin,
                               self.inner_width,
                               self.inner_height,
                               id='portrait_frame ')
        landscape_frame = Frame(self.leftMargin,
                                self.bottomMargin,
                                self.inner_height,
                                self.inner_width,
                                id='landscape_frame ')
        # portrait_frame = Frame(leftMargin, bottomMargin, width, height, id='portrait_frame ')
        # landscape_frame = Frame(leftMargin, bottomMargin, height, width, id='landscape_frame ')
        #
        self.doc.addPageTemplates([
            PageTemplate(id='portrait', frames=portrait_frame),
            PageTemplate(id='landscape',
                         frames=landscape_frame,
                         pagesize=landscape(A4)),
        ])
        # TODO: This was breaking the top header, but I don't know why?
        #  DDF 24 Feb 2020

        # Table for image and text at the top
        if input_filename is None:
            self.filename = self.no_input_filename_str
            self.full_filename = "an unsaved method file"
        else:
            self.filename = pathlib.Path(input_filename).name
            self.full_filename = input_filename

        self.title = title

        self.elements.append(self.make_report_header(title, self.filename))

        self.elements.append(Spacer(1, cm))
コード例 #7
0
    def report(self, title):
        doc = SimpleDocTemplate(
            self.buffer,
            # self.filename,
            rightMargin=35,
            leftMargin=50,
            topMargin=45,
            bottomMargin=31,
            title=self.filename,
            author='MBR author',
            creator='MBR report system creator',
            pagesize=self.pageSize)

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='TableHeader',
                           fontSize=11,
                           alignment=TA_CENTER,
                           fontName='RobotoBold'))
        styles.add(
            ParagraphStyle(name='ParagraphTitle',
                           fontSize=11,
                           alignment=TA_JUSTIFY,
                           fontName='RobotoBold'))
        styles.add(
            ParagraphStyle(name='Justify',
                           alignment=TA_JUSTIFY,
                           fontName='RobotoBold'))
        styles.add(
            ParagraphStyle(name='PageHeader',
                           fontSize=9,
                           alignment=TA_CENTER,
                           fontName='UbuntuLight'))
        styles.add(
            ParagraphStyle(name='PageHeaderContact',
                           fontSize=7,
                           alignment=TA_CENTER,
                           fontName='UbuntuLight'))
        styles.add(
            ParagraphStyle(name='PageTitle',
                           fontSize=14,
                           alignment=TA_CENTER,
                           fontName='UbuntuMedium'))
        styles.add(
            ParagraphStyle(name='PageFlightRoute',
                           fontSize=11,
                           alignment=TA_CENTER,
                           fontName='UbuntuMedium'))
        styles.add(
            ParagraphStyle(name='TypeInfoTitle',
                           fontSize=13,
                           alignment=TA_CENTER,
                           fontName='UbuntuMedium'))
        styles.add(
            ParagraphStyle(name='Index',
                           fontSize=13,
                           alignment=TA_JUSTIFY,
                           fontName='UbuntuMedium'))
        styles.add(
            ParagraphStyle(name='IndexCenter',
                           fontSize=13,
                           alignment=TA_CENTER,
                           fontName='UbuntuMedium'))
        styles.add(
            ParagraphStyle(name='Message',
                           fontSize=12,
                           leading=15,
                           fontName='UbuntuLight'))

        data = []
        data.append(Spacer(1, 12))
        title = 'FLIGHT DOCUMENTATION'
        data.append(Paragraph(title, styles['PageTitle']))
        data.append(Spacer(1, 12))
        airport_from = self.context['request_data']['airport_from']
        airport_to = self.context['request_data']['airport_to']
        flight = 'Flight #: ' + self.context['request_data']['number']
        spaces = '&nbsp;' * 110
        route = 'Route: ' + airport_from + '-' + airport_to
        data.append(
            Paragraph(flight + spaces + route, styles['PageFlightRoute']))
        data.append(Spacer(1, 12))

        #Observation and forecasts
        subtitle = 'Airport reports and forecasts, en-route warnings'
        data.append(Paragraph(subtitle, styles['TypeInfoTitle']))
        data.append(Spacer(1, 12))
        for k, v in self.context['observation'].items():
            data.append(Paragraph(k, styles['Index']))
            data.append(Spacer(1, 5))
            data.append(Paragraph(v['message'], styles['Message']))
            forecast = self.context['forecast'][k]['message']
            data.append(Spacer(1, 5))
            data.append(Paragraph(forecast, styles['Message']))
            data.append(Spacer(1, 5))
        data.append(PageBreak())

        # SIGMETs
        data.append(Spacer(1, 12))
        subtitle = 'SIGMET'
        data.append(Paragraph(subtitle, styles['TypeInfoTitle']))
        for k, v in self.context['sigmets'].items():
            data.append(Paragraph(k, styles['Index']))
            for sigmet in self.context['sigmets'][k]:
                data.append(Paragraph(sigmet['message'], styles['Message']))
        data.append(PageBreak())

        # AIRMETs
        if 'airmets' in self.context:
            data.append(Spacer(1, 12))
            subtitle = 'AIRMET'
            data.append(Paragraph(subtitle, styles['TypeInfoTitle']))
            for k, v in self.context['airmets'].items():
                data.append(Paragraph(k, styles['Index']))
                for airmet in self.context['airmets'][k]:
                    data.append(Paragraph(airmet['message'],
                                          styles['Message']))
            data.append(PageBreak())

        # GAMETS
        if 'gamets' in self.context:
            data.append(Spacer(1, 12))
            subtitle = 'GAMET'
            data.append(Paragraph(subtitle, styles['TypeInfoTitle']))
            for k, v in self.context['gamets'].items():
                data.append(Paragraph(k, styles['Index']))
                for gamet in self.context['gamets'][k]:
                    data.append(Paragraph(gamet['message'], styles['Message']))
            data.append(PageBreak())

    # Volcanic
        '''if self.context['gamets']:
            for k, v in self.context['gamets'].items():
                data.append(Paragraph(k, styles['Index']))
                for message in self.context['gamets'][k]:
                    data.append(Paragraph(message['message'], styles['Message']))
        '''
        for key, value in self.context.items():
            if key == 'wafc_charts':
                for date_time, regions in value.items():
                    for region, flightlevels in regions.items():
                        for flightlevel, datamap in flightlevels.items():
                            map_image = base64.b64decode(datamap['base64'])
                            buffer_map = io.BytesIO(map_image)
                            if (flightlevel == 'SM') or (flightlevel == 'SH'):
                                titlemap = 'WAFC forecast of SIGWX (SWM) for region' + str(
                                    region)
                            else:
                                titlemap = 'WAFC forecast of upper wind and upper-air temperature for FL' + str(
                                    flightlevel)
                            data.append(
                                Paragraph(titlemap, styles['TypeInfoTitle']))
                            data.append(
                                Paragraph('valid ' + str(date_time),
                                          styles['TypeInfoTitle']))
                            image = RotadedImage(buffer_map,
                                                 width=255 * mm,
                                                 height=176 * mm,
                                                 mask="auto")
                            data.append(image)
        data.append(PageBreak())

        #Radar meteorological phenomena chart
        map_image = base64.b64decode(self.context['phenomena_chart'][1])
        buffer_map = io.BytesIO(map_image)
        titlemap = 'Radar meteorological phenomena chart'
        data.append(Paragraph(titlemap, styles['TypeInfoTitle']))
        data.append(Spacer(1, 12))
        image = Image(buffer_map, width=435, height=335, mask="auto")
        data.append(Spacer(1, 12))
        data.append(image)
        data.append(Spacer(1, 12))

        #Radar echo heights chart
        map_image = base64.b64decode(self.context['heights_chart'][1])
        buffer_map = io.BytesIO(map_image)
        titlemap = 'Radar echo heights chart'
        data.append(Paragraph(titlemap, styles['TypeInfoTitle']))
        data.append(Spacer(1, 12))
        image = Image(buffer_map, width=435, height=335, mask="auto")
        data.append(image)

        # create document
        doc.build(data,
                  onFirstPage=self.pageNumber,
                  onLaterPages=self.pageNumber)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
コード例 #8
0
def comparison_graphs(comparison_values, location, emission):
    s = Spacer(9 * inch, .2 * inch)
    Elements.append(s)

    labels = []
    data = []
    comparison_values.append([location, emission])
    comparison_values.sort(key=lambda x: x[1])
    for pair in comparison_values:
        labels.append(pair[0])
        data.append(pair[1])
    location_index = labels.index(location)
    data = [data]
    '''
    Trial and error on making this centered and looking good; seems like if
    just inserted into the table, it moves all the way to the right; hence
    the x = -150 to center it, and -120 to move it downwards so it doesn't
    overlap with the top of the graph
    '''
    drawing = Drawing(0, 0)
    bc = VerticalBarChart()
    bc.x = -150
    bc.y = -120
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = data[0][-1] + data[0][-1] * .1
    #bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = labels
    for i in range(len(labels)):
        bc.bars[(0, i)].fillColor = colors.Color(166.0 / 255, 189.0 / 255,
                                                 219.0 / 255)
    bc.bars[(0,
             location_index)].fillColor = colors.Color(28.0 / 255, 144.0 / 255,
                                                       153.0 / 255)
    drawing.add(bc)
    #Elements.append(drawing)

    graph_data = [
        ['Emission Comparison'],
        [
            'CO2 emissions for the function if the computation had been performed elsewhere'
        ], [drawing]
    ]
    graph_table = Table(graph_data, [6 * inch],
                        [.25 * inch, .25 * inch, .25 * inch],
                        hAlign="CENTER")
    graph_table.setStyle(
        TableStyle([('FONT', (0, 0), (0, 0), "Times-Bold"),
                    ('FONT', (0, 1), (0, 1), "Times-Roman"),
                    ('FONTSIZE', (0, 0), (0, 0), 13),
                    ('FONTSIZE', (0, 1), (0, 1), 12),
                    ('ALIGN', (0, 0), (-1, -1), "CENTER")]))

    Elements.append(graph_table)
コード例 #9
0
ファイル: pdf.py プロジェクト: voszp/wger
def workout_view(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of the workout, without table for logs
    '''

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

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

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(
        response,
        pagesize=A4,
        # pagesize = landscape(A4),
        leftMargin=cm,
        rightMargin=cm,
        topMargin=0.5 * cm,
        bottomMargin=0.5 * cm,
        title=_('Workout'),
        author='wger Workout Manager',
        subject=_('Workout for %s') % request.user.username)

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

    # table data, here we will put the workout info
    data = []

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

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

    #
    # Iterate through the Workout
    #

    # Days
    for day in workout.canonical_representation['day_list']:
        set_count = 1
        day_markers.append(len(data))
        group_day_marker[day['obj'].id] = {
            'start': len(data),
            'end': len(data)
        }

        if not exercise_markers.get(day['obj'].id):
            exercise_markers[day['obj'].id] = []

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

        data.append([p])

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

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

                # Note: '+1' here because there's an emtpy cell between days
                exercise_markers[day['obj'].id].append(len(data) + 1)
                data.append([
                    set_count,
                    Paragraph(exercise['obj'].name, styleSheet["Small"]),
                    exercise['setting_text']
                ])
            set_count += 1

        data.append([''])
        group_day_marker[day['obj'].id]['end'] = len(data)

        # Set the widths and heights of rows and columns
        # Note: 'None' is treated as 'automatic'. Either there is only one value for the whole list
        #       or exactly one for every row/column
        colwidths = None
        rowheights = [None] * len(data)

    table_style = [
        ('FONT', (0, 0), (-1, -1), 'OpenSans'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),

        # Note: a padding of 3 seems to be the default
        ('LEFTPADDING', (0, 0), (-1, -1), 2),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 3),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
    ]

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

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

        # Manually set
        rowheights[marker - 1] = 5

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

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

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

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

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

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

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

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

    #
    # Add all elements to the document
    #

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

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

    # Append the table
    elements.append(t)

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

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

    # Create the HttpResponse object with the appropriate PDF headers.
    response[
        'Content-Disposition'] = 'attachment; filename=Workout-{0}-table.pdf'.format(
            id)
    response['Content-Length'] = len(response.content)
    return response
コード例 #10
0
    def preparar_pdf(self, grilla):
        datos = grilla.get_model()
        cant = len(datos)

        ubicacion_archivo = dialogo_guardar("Notas de Crédito por Compras")

        if ubicacion_archivo is not None:
            # Si no tiene la terminación .pdf se le agrega
            if ubicacion_archivo[-4:].lower() != ".pdf":
                ubicacion_archivo += ".pdf"

            story = []
            cabecera = cabecera_style()
            parrafo = parrafo_bodytext()
            head = tabla_celda_titulo()
            body_ce = tabla_celda_centrado()
            body_iz = tabla_celda_just_izquierdo()
            body_de = tabla_celda_just_derecho()

            story.append(Par("Notas de Crédito por Compras", cabecera))
            story.append(Spacer(0, 20))

            if self.obj("chk_01").get_active():  # Proveedor
                story.append(
                    Par(
                        "Notas de Crédito del Proveedor <b>" +
                        self.obj("txt_prov_02").get_text() + "</b>", parrafo))

            if self.obj("chk_02").get_active():  # Fecha
                story.append(
                    Par(
                        "Notas de Crédito expedidas entre el " + "<b>" +
                        cadena_fecha(self.fecha_ini) + "</b> y el " + "<b>" +
                        cadena_fecha(self.fecha_fin) + "</b>", parrafo))

            if self.obj("chk_03").get_active():  # Total
                if self.idTotal == 1:  # Entre
                    tipo, segundo = "entre", " y <b>" + \
                    str(self.obj("txt_total_fin").get_value()) + "</b>"
                elif self.idTotal == 2:  # Mayor que
                    tipo, segundo = "mayor que", ""
                elif self.idTotal == 3:  # Mayor o igual que
                    tipo, segundo = "mayor o igual que", ""
                elif self.idTotal == 4:  # Menor que
                    tipo, segundo = "menor que", ""
                elif self.idTotal == 5:  # Menor o igual que
                    tipo, segundo = "menor o igual que", ""
                story.append(
                    Par(
                        "Notas de Crédito expedidas por un Monto " + tipo +
                        " <b>" + str(self.obj("txt_total_ini").get_value()) +
                        " </b>" + segundo, parrafo))

            story.append(Spacer(0, 20))

            lista = [[
                Par("Nro. Timbrado", head),
                Par("Nro. Nota de Crédito", head),
                Par("Fecha", head),
                Par("Nro. Doc. Prov.", head),
                Par("Proveedor", head),
                Par("Total", head)
            ]]

            for i in range(0, cant):
                lista.append([
                    Par(str(datos[i][0]), body_ce),
                    Par(datos[i][1], body_ce),
                    Par(datos[i][2], body_ce),
                    Par(datos[i][3], body_ce),
                    Par(datos[i][4], body_iz),
                    Par(str(datos[i][5]), body_de)
                ])

            tabla = Table(lista, [100, 100, 150, 100, 175, 75])
            tabla = tabla_style(tabla)
            story.append(tabla)

            doc = SimpleDocTemplate(
                ubicacion_archivo,
                pagesize=landscape(A4),
                leftMargin=3 * cm,  # Margen Izquierdo
                rightMargin=3 * cm,  # Margen Derecho
                topMargin=2.5 * cm,  # Margen Superior
                bottomMargin=2.5 * cm,  # Margen Inferior
                allowSplitting=1,
                title="Notas de Crédito por Compras",
                author="Sistema Distribuidora")

            try:  # Generar Archivo
                doc.build(story)
                popen(ubicacion_archivo)
            except PermissionError as e:
                error_permiso_archivo(str(e))
コード例 #11
0
def equivs_and_emission_equivs(equivs_data, emissions_data):
    '''
    Creates a table with 2 columns, each with their own embedded table
    The embedded tables contain 2 vertically-stacked tables, one for the header
    and the other one for the actual data in order to have better alignment

    The first row of the 2nd vertically-stacked table is smaller than the rest in
    order to remove the extra space and make these tables look cohesive with the
    energy usage readings and energy mix tables

    Setup:
    * Table(data[array of arrays, one for each row], [column widths], [row heights])
    * Spacer(width, height)


    '''
    s = Spacer(9 * inch, .2 * inch)
    Elements.append(s)

    no_rows = 1
    no_cols = 1
    col_size = 4.5

    equivs_header_data = [["Assumed Carbon Equivalencies"]]

    # Table(data)
    equivs_header_table = Table(equivs_header_data, [3 * inch], [.25 * inch])
    equivs_header_table.setStyle(
        TableStyle([('FONT', (0, 0), (0, -1), "Times-Bold"),
                    ('FONTSIZE', (0, 0), (-1, -1), 13)]))

    equivs_data_table = Table(
        equivs_data, [1 * inch, 2 * inch],
        [0.17 * inch, 0.25 * inch, 0.25 * inch, 0.25 * inch],
        hAlign="LEFT")
    equivs_data_table.setStyle(
        TableStyle([('FONT', (0, 0), (-1, -1), "Times-Roman"),
                    ('FONTSIZE', (0, 0), (-1, -1), 12),
                    ('ALIGN', (0, 0), (0, -1), "RIGHT"),
                    ('VALIGN', (-1, -1), (-1, -1), "TOP")]))

    t1_data = [[equivs_header_table], [equivs_data_table]]

    t1 = Table(t1_data, [3 * inch])

    emissions_header_data = [["CO2 Emissions Equivalents"]]
    emissions_header_table = Table(emissions_header_data, [3 * inch],
                                   [.25 * inch])
    emissions_header_table.setStyle(
        TableStyle([('FONT', (0, 0), (0, -1), "Times-Bold"),
                    ('FONTSIZE', (0, 0), (-1, -1), 13)]))

    emissions_data_table = Table(emissions_data, [1.5 * inch, 2 * inch],
                                 [0.17 * inch, 0.25 * inch, 0.25 * inch],
                                 hAlign="LEFT")
    emissions_data_table.setStyle(
        TableStyle([('FONT', (0, 0), (-1, -1), "Times-Roman"),
                    ('FONTSIZE', (0, 0), (-1, -1), 12),
                    ('ALIGN', (0, 0), (0, -1), "RIGHT"),
                    ('VALIGN', (-1, -1), (-1, -1), "TOP")]))

    t2_data = [[emissions_header_table], [emissions_data_table]]

    t2 = Table(t2_data, [3 * inch])

    table_data = [(t1, t2)]
    t = Table(table_data, [4.25 * inch, 3 * inch], hAlign='CENTER')
    t.setStyle(TableStyle([('VALIGN', (-1, -1), (-1, -1), "TOP")]))
    Elements.append(t)
コード例 #12
0
logo = "logoC.png"
signature = "signature.png"
magName = "Oceaneering"
issueNum = 12
subPrice = "99.00"
limitedDate = "03/05/2020"
freeGift = "tin foil hat"
formatted_time = time.ctime()
full_name = "Magne Andersen"
address_parts = ["Vestre Svanholmen 24, 4313 Sandnes, Norway"]

im = Image(logo, 3 * inch, 1.3 * inch)
Story.append(im)
#im.hAlign = 'LEFT'

Story.append(Spacer(1, 42))
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
ptext = '<font size="10">%s</font>' % formatted_time
Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 12))
# Create return address
ptext = '<font size="10">%s</font>' % full_name
Story.append(Paragraph(ptext, styles["Normal"]))
for part in address_parts:
    ptext = '<font size="10">%s</font>' % part.strip()
    Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 42))
ptext = '<font size="10">Dear %s:</font>' % full_name.split()[0].strip()
Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 12))
コード例 #13
0
def _invoice_generate_german(invoice, f):
    _invoice_register_fonts()
    styles = _invoice_get_stylesheet()
    pagesize = pagesizes.A4

    def on_page(canvas, doc):
        canvas.saveState()
        canvas.setFont('OpenSans', 8)
        canvas.drawRightString(pagesize[0] - 20 * mm, 10 * mm,
                               _("Page %d") % (doc.page, ))

        for i, line in enumerate(invoice.footer_text.split('\n')[::-1]):
            canvas.drawCentredString(pagesize[0] / 2, 25 + (3.5 * i) * mm,
                                     line.strip())

        canvas.restoreState()

    def on_first_page(canvas, doc):
        canvas.setCreator('pretix.eu')
        canvas.setTitle(
            pgettext('invoice', 'Invoice {num}').format(num=invoice.number))

        canvas.saveState()
        canvas.setFont('OpenSans', 8)
        canvas.drawRightString(pagesize[0] - 20 * mm, 10 * mm,
                               _("Page %d") % (doc.page, ))

        for i, line in enumerate(invoice.footer_text.split('\n')[::-1]):
            canvas.drawCentredString(pagesize[0] / 2, 25 + (3.5 * i) * mm,
                                     line.strip())

        textobject = canvas.beginText(25 * mm, (297 - 15) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(pgettext('invoice', 'Invoice from').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLines(invoice.invoice_from.strip())
        canvas.drawText(textobject)

        textobject = canvas.beginText(25 * mm, (297 - 50) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(pgettext('invoice', 'Invoice to').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLines(invoice.invoice_to.strip())
        canvas.drawText(textobject)

        textobject = canvas.beginText(125 * mm, (297 - 50) * mm)
        textobject.setFont('OpenSansBd', 8)
        if invoice.is_cancellation:
            textobject.textLine(
                pgettext('invoice', 'Cancellation number').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(invoice.number)
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSansBd', 8)
            textobject.textLine(
                pgettext('invoice', 'Original invoice').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(invoice.refers.number)
        else:
            textobject.textLine(pgettext('invoice', 'Invoice number').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(invoice.number)
        textobject.moveCursor(0, 5)

        if invoice.is_cancellation:
            textobject.setFont('OpenSansBd', 8)
            textobject.textLine(
                pgettext('invoice', 'Cancellation date').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(date_format(invoice.date, "DATE_FORMAT"))
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSansBd', 8)
            textobject.textLine(
                pgettext('invoice', 'Original invoice date').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(date_format(invoice.refers.date,
                                            "DATE_FORMAT"))
            textobject.moveCursor(0, 5)
        else:
            textobject.setFont('OpenSansBd', 8)
            textobject.textLine(pgettext('invoice', 'Invoice date').upper())
            textobject.moveCursor(0, 5)
            textobject.setFont('OpenSans', 10)
            textobject.textLine(date_format(invoice.date, "DATE_FORMAT"))
            textobject.moveCursor(0, 5)

        canvas.drawText(textobject)

        textobject = canvas.beginText(165 * mm, (297 - 50) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(_('Order code').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLine(invoice.order.full_code)
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(_('Order date').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLine(date_format(invoice.order.datetime, "DATE_FORMAT"))
        canvas.drawText(textobject)

        textobject = canvas.beginText(125 * mm, (297 - 15) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(_('Event').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLine(str(invoice.event.name))
        if invoice.event.settings.show_date_to:
            textobject.textLines(
                _('{from_date}\nuntil {to_date}').format(
                    from_date=invoice.event.get_date_from_display(),
                    to_date=invoice.event.get_date_to_display()))
        else:
            textobject.textLine(invoice.event.get_date_from_display())
        canvas.drawText(textobject)

        canvas.restoreState()

    doc = BaseDocTemplate(f.name,
                          pagesize=pagesizes.A4,
                          leftMargin=25 * mm,
                          rightMargin=20 * mm,
                          topMargin=20 * mm,
                          bottomMargin=15 * mm)

    footer_length = 3.5 * len(invoice.footer_text.split('\n')) * mm
    frames_p1 = [
        Frame(doc.leftMargin,
              doc.bottomMargin,
              doc.width,
              doc.height - 75 * mm,
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=footer_length,
              id='normal')
    ]
    frames = [
        Frame(doc.leftMargin,
              doc.bottomMargin,
              doc.width,
              doc.height,
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=footer_length,
              id='normal')
    ]
    doc.addPageTemplates([
        PageTemplate(id='FirstPage',
                     frames=frames_p1,
                     onPage=on_first_page,
                     pagesize=pagesize),
        PageTemplate(id='OtherPages',
                     frames=frames,
                     onPage=on_page,
                     pagesize=pagesize)
    ])
    story = [
        NextPageTemplate('FirstPage'),
        Paragraph(
            pgettext('invoice', 'Invoice') if not invoice.is_cancellation else
            pgettext('invoice', 'Cancellation'), styles['Heading1']),
        Spacer(1, 5 * mm),
        NextPageTemplate('OtherPages'),
    ]

    if invoice.introductory_text:
        story.append(Paragraph(invoice.introductory_text, styles['Normal']))
        story.append(Spacer(1, 10 * mm))

    taxvalue_map = defaultdict(Decimal)
    grossvalue_map = defaultdict(Decimal)

    tstyledata = [
        ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
        ('FONTNAME', (0, 0), (-1, 0), 'OpenSansBd'),
        ('FONTNAME', (0, -1), (-1, -1), 'OpenSansBd'),
        ('LEFTPADDING', (0, 0), (0, -1), 0),
        ('RIGHTPADDING', (-1, 0), (-1, -1), 0),
    ]
    tdata = [(
        pgettext('invoice', 'Description'),
        pgettext('invoice', 'Tax rate'),
        pgettext('invoice', 'Net'),
        pgettext('invoice', 'Gross'),
    )]
    total = Decimal('0.00')
    for line in invoice.lines.all():
        tdata.append((
            line.description,
            lformat("%.2f", line.tax_rate) + " %",
            lformat("%.2f", line.net_value) + " " + invoice.event.currency,
            lformat("%.2f", line.gross_value) + " " + invoice.event.currency,
        ))
        taxvalue_map[line.tax_rate] += line.tax_value
        grossvalue_map[line.tax_rate] += line.gross_value
        total += line.gross_value

    tdata.append([
        pgettext('invoice', 'Invoice total'), '', '',
        lformat("%.2f", total) + " " + invoice.event.currency
    ])
    colwidths = [a * doc.width for a in (.55, .15, .15, .15)]
    table = Table(tdata, colWidths=colwidths, repeatRows=1)
    table.setStyle(TableStyle(tstyledata))
    story.append(table)

    story.append(Spacer(1, 15 * mm))

    if invoice.payment_provider_text:
        story.append(Paragraph(invoice.payment_provider_text,
                               styles['Normal']))

    if invoice.additional_text:
        story.append(Paragraph(invoice.additional_text, styles['Normal']))
        story.append(Spacer(1, 15 * mm))

    tstyledata = [
        ('SPAN', (1, 0), (-1, 0)),
        ('ALIGN', (2, 1), (-1, -1), 'RIGHT'),
        ('LEFTPADDING', (0, 0), (0, -1), 0),
        ('RIGHTPADDING', (-1, 0), (-1, -1), 0),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
    ]
    tdata = [('', pgettext('invoice', 'Included taxes'), '', '', ''),
             ('', pgettext('invoice',
                           'Tax rate'), pgettext('invoice', 'Net value'),
              pgettext('invoice', 'Gross value'), pgettext('invoice', 'Tax'))]

    for rate, gross in grossvalue_map.items():
        if line.tax_rate == 0:
            continue
        tax = taxvalue_map[rate]
        tdata.append((
            '',
            lformat("%.2f", rate) + " %",
            lformat("%.2f", (gross - tax)) + " " + invoice.event.currency,
            lformat("%.2f", gross) + " " + invoice.event.currency,
            lformat("%.2f", tax) + " " + invoice.event.currency,
        ))

    if len(tdata) > 2:
        colwidths = [a * doc.width for a in (.45, .10, .15, .15, .15)]
        table = Table(tdata, colWidths=colwidths, repeatRows=2)
        table.setStyle(TableStyle(tstyledata))
        story.append(table)

    doc.build(story)
    return doc
コード例 #14
0
    def __call__(self, value, name_vue, request):

        if request is not None:
            response = request.response
            ct = response.content_type
            if ct == response.default_content_type:
                response.content_type = 'application/pdf'
        fout = io.BytesIO()
        cols = value.get('header', [])
        rows = value.get('rows', [])
        data = []

        for obj in rows:
            row = []
            for item in obj:
                row.append(item)
            data.append(row)

        table_font_size = 9
        if name_vue == "V_Qry_VIndiv_MonitoredLostPostReleaseIndividuals_LastStations":
            table_font_size = 8
            for key in range(len(cols)):
                if cols[key] == 'DATE':
                    cols[key] = 'Date lastpos'
                elif cols[key] == 'Name_signal_type':
                    cols[key] = 'Signal'
                elif cols[key] == 'MonitoringStatus@Station':
                    cols[key] = 'Monitoring st.'
                elif cols[key] == 'SurveyType@Station':
                    cols[key] = 'Servey type'
            cols.append('Date')
        else:
            cols.append('Date de saisie')
        cols.append('Vu')
        cols.append('Entendu')
        cols.append('Perdu')
        cols.append('Mort')
        cols.append('Repro')
        cols.append('No check')

        data.insert(0, cols)
        styleSheet = getSampleStyleSheet()
        doc = SimpleDocTemplate(fout,
                                pagesize=landscape(A4),
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=20,
                                bottomMargin=18)
        Story = []
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
        Story.append(Paragraph("Export " + name_vue, styleSheet['Title']))
        Story.append(Spacer(0, 5 * mm))
        if name_vue == "V_Qry_VIndiv_MonitoredLostPostReleaseIndividuals_LastStations":
            Story.append(
                Paragraph(
                    "Nom de l\'observateur:_____________________________",
                    styleSheet['BodyText']))
            Story.append(
                Paragraph(
                    "Secteur de suivi: _____________________ Date de Saisie: _________________",
                    styleSheet['BodyText']))
            Story.append(Spacer(0, 5 * mm))

        table_style = [('GRID', (0, 0), (-1, -1), 1, colors.black),
                       ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                       ('LEFTPADDING', (0, 0), (-1, -1), 3),
                       ('RIGHTPADDING', (0, 0), (-1, -1), 3),
                       ('FONTSIZE', (0, 0), (-1, -1), table_font_size),
                       ('FONTNAME', (0, 0), (-1, 0), 'Times-Bold')]
        frame1 = Frame(doc.leftMargin,
                       doc.height - 5 * 25.4 * mm,
                       doc.width,
                       5 * 25.4 * mm,
                       leftPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       bottomPadding=0,
                       id='frame1')

        spreadsheet_table = SpreadsheetTable(data, repeatRows=1)
        spreadsheet_table.setStyle(table_style)
        Story.append(spreadsheet_table)
        Story.append(PageBreak())
        doc.build(Story,
                  onFirstPage=self.addPageNumber,
                  onLaterPages=self.addPageNumber)
        pdf = fout.getvalue()
        fout.close()
        return pdf
コード例 #15
0
def generate_crs(response, ovc_data, ovc_items):

    doc = SimpleDocTemplate(response,
                            rightMargin=.5 * cm,
                            leftMargin=.5 * cm,
                            topMargin=1.5 * cm,
                            bottomMargin=1.5 * cm,
                            title="Case Record Sheet",
                            author='CPIMS',
                            subject="CPIMS - Case Record Sheet",
                            creator="CPIMS",
                            keywords="CPIMS, DCS, Case Record Sheet")

    story = []
    # Styles
    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=7))
    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=12))
    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=7,
                       alignment=TA_LEFT))
    styles.add(
        ParagraphStyle(name='Line_Title',
                       font='Helvetica-Bold',
                       fontSize=10,
                       alignment=TA_LEFT))
    styles.add(
        ParagraphStyle(name='Line_Label_Center',
                       font='Helvetica-Bold',
                       fontSize=12,
                       leading=10,
                       alignment=TA_CENTER))

    # Get company information
    data1 = [[Image(logo_path, 1.8 * cm, 1.5 * cm)]]
    tt1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    sllc = styles["Line_Label_Center"]
    slds = styles["Line_Data_Small"]

    story.append(tt1)
    story.append(Paragraph("<b>DEPARTMENT OF CHILDREN SERVICES</b>", sllc))

    story.append(Spacer(0.1 * cm, .2 * cm))

    data1 = [[
        Paragraph('<b>CASE RECORD SHEET - A</b>', styles["Line_Title"]),
        Paragraph("<b><i>Rev. Aug '18</i></b>", slds)
    ]]
    t1 = Table(data1, colWidths=(None, 2.0 * cm), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .1 * cm))
    intro = 'This form to be filled whenever a child protection issue is '
    intro += 'brought before a child protection office, institution '
    intro += ' or facility.'
    data1 = [[
        Paragraph(intro, styles["Line_Label"]),
    ]]
    t1 = Table(data1, colWidths=(None))
    t1.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .1 * cm))
    data1 = [[
        Paragraph('<b>County:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['county'], styles["Line_Data"]),
        Paragraph('<b>Sub County:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['sub_county'], styles["Line_Data"]),
        Paragraph('<b>Institution:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['institution'], styles["Line_Data"])
    ]]

    t1 = Table(data1,
               colWidths=(1.4 * cm, 2.7 * cm, 2.0 * cm, 3.5 * cm, 2.0 * cm,
                          None))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (1, 0), (1, 1), 0.25, colors.black),
            ('INNERGRID', (3, 0), (3, 1), 0.25, colors.black),
            ('INNERGRID', (5, 0), (5, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>Case Serial No:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['case_serial'], styles["Line_Data_Small"]),
        Paragraph('<b>Date of Reporting:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['case_date'], styles["Line_Data_Small"]),
        Paragraph('<b>Contact Address / Email:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['reporter_address'], slds)
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 4.3 * cm, 2.1 * cm, 4.0 * cm, 2.5 * cm,
                          4.3 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Case Reported by (Name):</b>', styles["Line_Label"]),
        Paragraph(ovc_data['reporter_names'], styles["Line_Data_Small"]),
        Paragraph('<b>Relationship to Child:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['reporter_type'], styles["Line_Data_Small"]),
        Paragraph('<b>Telephone:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['reporter_tel'], styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 4.3 * cm, 2.1 * cm, 4.0 * cm, 2.5 * cm,
                          4.3 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)

    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>PERSONAL DETAILS OF THE CHILD</b>', styles["Line_Title"])
    ]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>Name of Child:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['child_name'], styles["Line_Data_Small"]),
        Paragraph('<b>Date of Birth:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['ovc_dob'], styles["Line_Data_Small"]),
        Paragraph('<b>Sex:</b>', styles["Line_Label"]),
        Paragraph('Male', styles["Line_Label"]),
        get_check(ovc_data['sex'], 'SMAL'),
        Paragraph('Female', styles["Line_Data_Small"]),
        get_check(ovc_data['sex'], 'SFEM'),
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 7.0 * cm, 1.5 * cm, 2.8 * cm, 1.9 * cm,
                          1.4 * cm, 0.6 * cm, 1.4 * cm, 0.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (5, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Child in School:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Name of School:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Class:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Category of School:</b>', styles["Line_Label"]),
        Paragraph('Formal', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Informal', styles["Line_Data_Small"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 1.0 * cm, 2.0 * cm, 4.0 * cm, 1.5 * cm,
                          2.8 * cm, 1.9 * cm, 1.4 * cm, 0.6 * cm, 1.4 * cm,
                          0.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (7, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Tribe / Ethnicity:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['tribe'], styles["Line_Data_Small"]),
        Paragraph('<b>Name of closest friends of child: <sup>1</sup></b>',
                  styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Religion:</b>', styles["Line_Label"]),
        Paragraph('Protestant', styles["Line_Label"]),
        get_check(ovc_data['religion'], 'RECH'),
        Paragraph('Muslim', styles["Line_Label"]),
        get_check(ovc_data['religion'], 'REMU'),
        Paragraph('Catholic', styles["Line_Label"]),
        get_check(ovc_data['religion'], 'RECH'),
        Paragraph('Other', styles["Line_Data_Small"]),
        get_check(ovc_data['religion'], 'REOT'),
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 3.0 * cm, 2.5 * cm, 2.1 * cm, 1.6 * cm,
                          1.6 * cm, 0.5 * cm, 1.4 * cm, 0.5 * cm, 1.4 * cm,
                          0.6 * cm, 1.4 * cm, 0.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (5, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Mental Condition:</b>', styles["Line_Label"]),
        Paragraph('Normal', styles["Line_Data_Small"]),
        get_check(ovc_data['mental_cond'], 'MNRM'),
        Paragraph('Challenged', styles["Line_Label"]),
        get_check(ovc_data['mental_cond'], 'MCAV,MCAU'),
        Paragraph('<b>Physical Condition:</b>', styles["Line_Label"]),
        Paragraph('Normal', styles["Line_Data_Small"]),
        get_check(ovc_data['phy_cond'], 'PNRM'),
        Paragraph('Challenged', styles["Line_Label"]),
        get_check(ovc_data['phy_cond'], 'PHAV,PHAU'),
        Paragraph('<b>Other Medical Condition:</b>', styles["Line_Label"]),
        Paragraph('Normal', styles["Line_Label"]),
        get_check(ovc_data['other_cond'], 'CHNM'),
        Paragraph('Chronic', styles["Line_Data_Small"]),
        get_check(ovc_data['other_cond'], 'CHRO'),
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 1.4 * cm, 0.6 * cm, 1.9 * cm, 0.6 * cm,
                          2.0 * cm, 1.4 * cm, 0.6 * cm, 1.9 * cm, 0.6 * cm,
                          2.2 * cm, 1.4 * cm, 0.6 * cm, 1.4 * cm, 0.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (1, 0), 0.25, colors.black),
            ('INNERGRID', (4, 0), (6, 0), 0.25, colors.black),
            ('INNERGRID', (9, 0), (11, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Hobbies:</b>', styles["Line_Label"]),
        Paragraph('Sports', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Movies', styles["Line_Data_Small"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Music', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Dancing', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Reading', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('<b>Child has Birth Certificate:</b>', styles["Line_Label"]),
        Paragraph('Yes', styles["Line_Label"]),
        get_check(ovc_data['bcert'], 'AYES'),
        Paragraph('No', styles["Line_Label"]),
        get_check(ovc_data['bcert'], 'ANNO'),
        Paragraph('Refer to CRD.', styles["Line_Data_Small"]),
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 1.4 * cm, 0.6 * cm, 1.4 * cm, 0.6 * cm,
                          1.2 * cm, 0.6 * cm, 1.4 * cm, 0.6 * cm, 1.4 * cm,
                          0.6 * cm, 2.4 * cm, 1.0 * cm, 0.6 * cm, 0.8 * cm,
                          0.6 * cm, 2.0 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (1, 0), 0.25, colors.black),
            ('INNERGRID', (10, 0), (12, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # SIBLINGS
    data1 = [[Paragraph('<b>SIBLINGS</b>', styles["Line_Title"])]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [
        [
            Paragraph('<b>No.</b>', styles["Line_Label"]),
            Paragraph('<b>Name</b>', styles["Line_Label"]),
            Paragraph('<b>D.O.B</b>', styles["Line_Label"]),
            Paragraph('<b>Sex</b>', styles["Line_Label"]),
            Paragraph('<b>Name of School</b>', styles["Line_Label"]),
            Paragraph('<b>Class</b>', styles["Line_Label"]),
            Paragraph('<b>Remarks</b>', styles["Line_Label"])
        ],
    ]

    t1 = Table(data1,
               colWidths=(0.9 * cm, 5.0 * cm, 2.5 * cm, 1.5 * cm, 5 * cm,
                          1.5 * cm, 3.2 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    siblings = ovc_items['siblings']
    items = [{'sibling': i} for i in range(1, 9)]
    data1 = [[
        Paragraph(str(product['sibling']), styles["Line_Data"]),
        Paragraph(str(siblings[product['sibling']]['name']),
                  styles["Line_Data"]),
        Paragraph(str(siblings[product['sibling']]['dob']),
                  styles["Line_Data"]),
        Paragraph(str(siblings[product['sibling']]['sex']),
                  styles["Line_Data"]), '', '',
        Paragraph(str(siblings[product['sibling']]['remark']),
                  styles["Line_Data"])
    ] for product in items]

    t1 = Table(data1,
               colWidths=(0.9 * cm, 5.0 * cm, 2.5 * cm, 1.5 * cm, 5 * cm,
                          1.5 * cm, 3.2 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # HOME PARTICULARS
    data1 = [[
        Paragraph('<b>HOME PARTICULARS OF THE CHILD</b>', styles["Line_Title"])
    ]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>County:<br/></b>', styles["Line_Label"]),
        Paragraph(ovc_data['child_county'], styles["Line_Data_Small"]),
        Paragraph('<b>Sub-County:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['child_sub_county'], styles["Line_Data_Small"]),
        Paragraph('<b>Village/Estate:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    t1 = Table(data1,
               colWidths=(2.4 * cm, 4.3 * cm, 2.1 * cm, 4.0 * cm, 2.5 * cm,
                          4.3 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Ward:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['child_ward'], styles["Line_Data_Small"]),
        Paragraph('<b>Nearest Land Mark:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1, colWidths=(2.4 * cm, 4.3 * cm, 2.1 * cm, 10.8 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    hes_txt = '<b>Household Economic Status (Income):</b>'
    data1 = [[
        Paragraph('<b>Family Status:</b>', styles["Line_Label"]),
        Paragraph('Parents living together', styles["Line_Label"]),
        get_check(ovc_data['family_status'], ''),
        Paragraph('Parents not living together', styles["Line_Label"]),
        get_check(ovc_data['family_status'], 'FSPN'),
        Paragraph(hes_txt, styles["Line_Label"]),
        Paragraph('Low', styles["Line_Label"]),
        get_check(ovc_data['hes_status'], 'LINC'),
        Paragraph('Middle', styles["Line_Label"]),
        get_check(ovc_data['hes_status'], 'MINC'),
        Paragraph('High', styles["Line_Label"]),
        get_check(ovc_data['hes_status'], 'HINC'),
        Paragraph('Unknown', styles["Line_Label"]),
        get_check(ovc_data['hes_status'], 'UINC')
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.4 * cm, 2.6 * cm, 0.6 * cm, 2.6 * cm, 0.6 * cm,
                          3.1 * cm, 1.1 * cm, 0.6 * cm, 1.4 * cm, 0.7 * cm,
                          1.1 * cm, 0.7 * cm, 1.5 * cm, 0.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (1, 0), 0.25, colors.black),
            ('INNERGRID', (4, 0), (6, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # PARENTS PARTICULARS
    data1 = [[Paragraph('<b>PARENTS PARTICULARS</b>', styles["Line_Title"])]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>Name</b>', styles["Line_Label"]),
        Paragraph('<b>Relationship</b>', styles["Line_Label"]),
        Paragraph('<b>ID No.</b>', styles["Line_Label"]),
        Paragraph('<b>Date of Birth</b>', styles["Line_Label"]),
        Paragraph('<b>Telephone</b>', styles["Line_Label"]),
        Paragraph('<b>Village/Estate</b>', styles["Line_Label"]),
        Paragraph('<b>Occupation</b>', styles["Line_Label"]),
        Paragraph('<b>Education<sup>2</sup></b>', styles["Line_Label"]),
        Paragraph('<b>Alive</b>', styles["Line_Label"])
    ]]

    t1 = Table(data1,
               colWidths=(4.5 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm,
                          2.1 * cm, 2.0 * cm, 1.8 * cm, 1.1 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    sld = styles["Line_Data"]
    story.append(t1)
    parents_items = {1: 'Father', 2: 'Mother'}
    parents = ovc_data['parents']
    items = [{'parent': 1}, {'parent': 2}]
    data1 = [[
        Paragraph(str(parents[product['parent']]['name']), sld),
        Paragraph(str(parents_items[product['parent']]), sld), '',
        Paragraph(str(parents[product['parent']]['dob']), sld), '', '', '', '',
        ''
    ] for product in items]

    t1 = Table(data1,
               colWidths=(4.5 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm,
                          2.1 * cm, 2.0 * cm, 1.8 * cm, 1.1 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # CAREGIVERS
    data1 = [[Paragraph('<b>CAREGIVER PARTICULARS</b>', styles["Line_Title"])]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .1 * cm))
    data1 = [[
        Paragraph('<b>Relationship:</b>', styles["Line_Label"]),
        Paragraph('Foster Parent', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Guardian', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Next of Kin', styles["Line_Label"]),
        Image(unchecked_image_path, .25 * cm, .25 * cm),
        Paragraph('Select as appropriate for caregiver', styles["Line_Label"]),
    ]]
    t1 = Table(data1,
               colWidths=(2.5 * cm, 2.0 * cm, 0.6 * cm, 1.5 * cm, 0.6 * cm,
                          2.0 * cm, 0.6 * cm, None))
    t1.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .1 * cm))
    data1 = [
        [
            Paragraph('<b>Name</b>', styles["Line_Label"]),
            Paragraph('<b>Sex</b>', styles["Line_Label"]),
            Paragraph('<b>Relationship</b>', styles["Line_Label"]),
            Paragraph('<b>ID No.</b>', styles["Line_Label"]),
            Paragraph('<b>Date of Birth</b>', styles["Line_Label"]),
            Paragraph('<b>Telephone</b>', styles["Line_Label"]),
            Paragraph('<b>Village/Estate</b>', styles["Line_Label"]),
            Paragraph('<b>Occupation</b>', styles["Line_Label"]),
            Paragraph('<b>Education<sup>2</sup></b>', styles["Line_Label"])
        ],
    ]

    t1 = Table(data1,
               colWidths=(4.5 * cm, 1.1 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm,
                          2.0 * cm, 2.1 * cm, 2.0 * cm, 1.8 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    items = [{'caregiver': 1}, {'caregiver': 2}]
    caregivers = ovc_data['caregivers']
    data1 = [[
        Paragraph(str(caregivers[product['caregiver']]['name']), sld), '', '',
        '', '', '', '', '', ''
    ] for product in items]

    t1 = Table(data1,
               colWidths=(4.5 * cm, 1.1 * cm, 2.0 * cm, 2.0 * cm, 2.0 * cm,
                          2.0 * cm, 2.1 * cm, 2.0 * cm, 1.8 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    # story.append(Spacer(0.5 * cm, 2.5 * cm))
    story.append(PageBreak())
    # CASE HISTORY
    data1 = [[
        Paragraph('<b>CASE HISTORY OF THE CHILD</b>', styles["Line_Title"])
    ]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>Date of Event / incident:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['case_date'], styles["Line_Data_Small"]),
        Paragraph('<b>Place of Event / incident:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['case_place'], styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 7.0 * cm, 2.6 * cm, 7.0 * cm),
               rowHeights=[1.2 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Alleged Perpetrator / Offender:</b>',
                  styles["Line_Label"]),
        Paragraph(ovc_data['perpetrator'], styles["Line_Data_Small"]),
        Paragraph('<b>Relationship to the Child:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['perpetrator_relation'], styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 7.0 * cm, 2.6 * cm, 7.0 * cm),
               rowHeights=[1.2 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Case category:</b>', styles["Line_Label"]),
        Paragraph(ovc_data['case_category'], styles["Line_Data_Small"]),
        Paragraph('<b>Specific issue about the case:</b>',
                  styles["Line_Label"]),
        Paragraph(ovc_data['case_remarks'], styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 7.0 * cm, 2.6 * cm, 7.0 * cm),
               rowHeights=[1.2 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Nature of case:</b>', styles["Line_Label"]),
        Paragraph('One off event', styles["Line_Label"]),
        get_check(ovc_data['case_nature'], 'OOEV'),
        Paragraph('Chronic / On going event', styles["Line_Label"]),
        get_check(ovc_data['case_nature'], 'OCGE'),
        Paragraph('Emergency', styles["Line_Label"]),
        get_check(ovc_data['case_nature'], 'OCME'),
        Paragraph('<b>Risk Level:</b>', styles["Line_Label"]),
        Paragraph('Low', styles["Line_Label"]),
        get_check(ovc_data['risk_level'], 'RLLW'),
        Paragraph('Medium', styles["Line_Label"]),
        get_check(ovc_data['risk_level'], 'RLMD'),
        Paragraph('High', styles["Line_Label"]),
        get_check(ovc_data['risk_level'], 'RLHG')
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 1.5 * cm, 0.6 * cm, 1.9 * cm, 0.6 * cm,
                          1.8 * cm, 0.6 * cm, 2.6 * cm, 1.5 * cm, 0.6 * cm,
                          1.9 * cm, 0.6 * cm, 1.8 * cm, 0.6 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (1, 0), 0.25, colors.black),
            ('INNERGRID', (6, 0), (8, 0), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Needs of the Child:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 8.3 * cm, 8.3 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Action Taken (Intervention):</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1, colWidths=(2.9 * cm, 16.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    refto = [[
        Paragraph('<b>State Agency (Specify):</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Reason for referral:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ],
             [
                 Paragraph('<b>Non-State Agency (Specify):</b>',
                           styles["Line_Label"]),
                 Paragraph('', styles["Line_Data_Small"]),
                 Paragraph('<b>Reason for referral:</b>',
                           styles["Line_Label"]),
                 Paragraph('', styles["Line_Data_Small"])
             ]]
    rt0 = Table(refto, colWidths=(4.0 * cm, None, 3.0 * cm, None))
    rt0.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (0, 1), 0.25, colors.black),
            ('INNERGRID', (1, 0), (1, 1), 0.25, colors.black),
            ('INNERGRID', (2, 0), (2, 1), 0.25, colors.black),
            ('INNERGRID', (3, 0), (3, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    data1 = [[Paragraph('<b>Refferal to:</b>', styles["Line_Label"]), rt0]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1, colWidths=(2.9 * cm, 16.6 * cm))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # RECOMMENDATIONS
    data1 = [[
        Paragraph(
            '<b>RECOMMENDATIONS FOR FURTHER ASSISTANCE BASED ON THE BEST INTEREST OF THE CHILD (BIC)</b>',
            styles["Line_Title"])
    ]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [['']]
    t1 = Table(data1, colWidths=(19.6 * cm), rowHeights=[1.8 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (1, 0), 0.25, colors.black),
            ('INNERGRID', (0, 1), (1, 1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [[
        Paragraph('<b>Name of Officer:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Signature:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 7.0 * cm, 2.7 * cm, 7.0 * cm),
               rowHeights=[0.8 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    data1 = [[
        Paragraph('<b>Designation:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"]),
        Paragraph('<b>Date:</b>', styles["Line_Label"]),
        Paragraph('', styles["Line_Data_Small"])
    ]]

    # t1 = Table(data1, colWidths=(3 * cm, None, 4.5 * cm,))
    t1 = Table(data1,
               colWidths=(2.9 * cm, 7.0 * cm, 2.7 * cm, 7.0 * cm),
               rowHeights=[0.8 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    # FOLLOW UP
    data1 = [[
        Paragraph(
            '<b>FOLLOW UP INFORMATION (INDICATE ANY PROGRESS FOR FURTHER INVERVENTION GIVEN)</b>',
            styles["Line_Title"])
    ]]
    t1 = Table(data1, colWidths=(None, ), rowHeights=[0.5 * cm])
    t1.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), '#a7a5a5'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .2 * cm))
    data1 = [
        [
            Paragraph('<b>Date</b>', styles["Line_Label"]),
            Paragraph('<b>Follow Up Status</b>', styles["Line_Label"]),
            Paragraph('<b>Comment</b>', styles["Line_Label"]),
            Paragraph('<b>Officer</b>', styles["Line_Label"])
        ],
    ]

    t1 = Table(data1,
               colWidths=(3.0 * cm, 4.5 * cm, 6.0 * cm, 6.1 * cm),
               rowHeights=[0.6 * cm])
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    t0 = Table([[Paragraph('Name', styles["Line_Label"])],
                [Paragraph('Designation', styles["Line_Label"])],
                [Paragraph('Signature', styles["Line_Label"])]],
               colWidths=(None))
    t0.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    items = [{'followup': i} for i in range(1, 4)]
    data1 = [['', '', '', t0] for product in items]

    t1 = Table(data1, colWidths=(3.0 * cm, 4.5 * cm, 6.0 * cm, 6.1 * cm))

    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
    story.append(t1)
    # FOOTER
    story.append(Spacer(0.1 * cm, .2 * cm))
    story.append(
        Table([[
            Paragraph(
                'I DECLARE THE INFORMATION CONTAINED IN THIS '
                'DOCUMENT TO BE TRUE AND CORRECT AS RECORDED IN CPIMS',
                styles["Line_Label"])
        ]]))

    story.append(Spacer(0.1 * cm, .2 * cm))

    # TODO: signature could be image ? Date could be sign_date ?
    # TODO: signature, date
    data1 = [[
        '', '',
        Paragraph(ovc_data['document_date'], styles["Line_Data_Large"])
    ],
             [
                 Paragraph(
                     'SIGNATURE OF SCCO (Must be signed for official use.)',
                     styles["Line_Label"]), '',
                 Paragraph('DATE', styles["Line_Label"])
             ]]

    t1 = Table(data1, colWidths=(None, 2 * cm, None))
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (0, 1), 0.25, colors.black),
            ('INNERGRID', (2, 0), (2, 1), 0.25, colors.black),
        ]))

    story.append(t1)

    doc.build(story, canvasmaker=FooterCanvas)
コード例 #16
0
ファイル: pdf.py プロジェクト: voszp/wger
def workout_log(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of the given workout

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

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

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

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(
        response,
        pagesize=A4,
        # pagesize = landscape(A4),
        leftMargin=cm,
        rightMargin=cm,
        topMargin=0.5 * cm,
        bottomMargin=0.5 * cm,
        title=_('Workout'),
        author='wger Workout Manager',
        subject=_('Workout for %s') % request.user.username)

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

    # Set the title
    p = Paragraph(
        '<para align="center"><strong>%(description)s</strong></para>' %
        {'description': workout}, styleSheet["HeaderBold"])
    elements.append(p)
    elements.append(Spacer(10 * cm, 0.5 * cm))

    # Iterate through the Workout and render the training days
    for day in workout.canonical_representation['day_list']:
        elements.append(render_workout_day(day, nr_of_weeks=7))
        elements.append(Spacer(10 * cm, 0.5 * cm))

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    elements.append(
        render_footer(request.build_absolute_uri(workout.get_absolute_url())))

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

    # Create the HttpResponse object with the appropriate PDF headers.
    response[
        'Content-Disposition'] = 'attachment; filename=Workout-{0}-log.pdf'.format(
            id)
    response['Content-Length'] = len(response.content)
    return response
コード例 #17
0
def generate_report(session: CashdeskSession) -> str:
    """
    Generates a closing report for a CashdeskSession; returns the path to the
    report PDF.
    """
    _buffer = BytesIO()
    doc = get_default_document(_buffer, footer=EventSettings.objects.get().report_footer)
    style = get_paragraph_style()

    # Header: info text and qr code
    title_str = '[{}] Kassenbericht #{}'.format(EventSettings.objects.get().short_name, session.pk)
    title = Paragraph(title_str, style['Heading1'])
    tz = timezone.get_current_timezone()
    text = """{user} an {cashdesk}<br/>{start} – {end}""".format(
        user=session.user.get_full_name(),
        cashdesk=session.cashdesk,
        start=session.start.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S'),
        end=session.end.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S'),
    )
    info = Paragraph(text, style['Normal'])
    logo = scale_image(get_qr_image(session), 100)

    header = Table(
        data=[[[title, info], logo], ],
        colWidths=[doc.width / 2] * 2,
        style=TableStyle([
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('VALIGN', (0, 0), (1, 0), 'TOP'),
        ]),
    )

    # Sales table
    sales_heading = Paragraph('Tickets', style['Heading3'])
    data = [['Ticket', 'Einzelpreis', 'Presale', 'Verkauf', 'Stornos', 'Gesamt'], ]
    sales_raw_data = session.get_product_sales()
    sales = [[p['product'].name, CURRENCY.format(p['value_single']), p['presales'], p['sales'],
              p['reversals'], CURRENCY.format(p['value_total'])]
             for p in sales_raw_data]
    data += sales
    data += [['', '', '', '', '', CURRENCY.format(sum([p['value_total'] for p in sales_raw_data]))]]
    last_row = len(data) - 1
    sales = Table(
        data=data,
        colWidths=[120] + [(doc.width - 120) / 5] * 5,
        style=TableStyle([
            ('FONTSIZE', (0, 0), (5, last_row), FONTSIZE),
            # TODO: register bold font and use here: ('FACE', (0,0), (3,0), 'boldfontname'),
            ('ALIGN', (0, 0), (0, last_row), 'LEFT'),
            ('ALIGN', (1, 0), (5, last_row), 'RIGHT'),
            ('LINEABOVE', (0, 1), (5, 1), 1.0, colors.black),
            ('LINEABOVE', (5, last_row), (5, last_row), 1.2, colors.black),
        ]),
    )

    # Items table
    items_heading = Paragraph('Auszählung', style['Heading3'])
    data = [['', 'Einzählung', 'Umsatz', 'Auszählung', 'Differenz'], ]

    # geld immer decimal mit € und nachkommastellen
    cash_transactions = session.get_cash_transaction_total()
    cash = [['Bargeld',
             CURRENCY.format(session.cash_before),
             CURRENCY.format(cash_transactions),
             CURRENCY.format(session.cash_after),
             CURRENCY.format(session.cash_before + cash_transactions - session.cash_after)], ]
    items = [
        [d['item'].name, d['movements'], d['transactions'], abs(d['final_movements']), d['total']]
        for d in session.get_current_items()
    ]
    last_row = len(items) + 1
    items = Table(
        data=data + cash + items,
        colWidths=[120] + [(doc.width - 120) / 4] * 4,
        style=TableStyle([
            ('FONTSIZE', (0, 0), (4, last_row), FONTSIZE),
            # TODO: register bold font and use here: ('FACE', (0,0), (3,0), 'boldfontname'),
            ('ALIGN', (0, 0), (0, last_row), 'LEFT'),
            ('ALIGN', (1, 0), (4, last_row), 'RIGHT'),
            ('LINEABOVE', (0, 1), (4, 1), 1.0, colors.black),
        ]),
    )

    # Signatures
    col_width = (doc.width - 35) / 2
    signatures = Table(
        data=[['Kassierer/in: {}'.format(session.user.get_full_name()), '',
               'Ausgezählt durch {}'.format(session.backoffice_user_after.get_full_name())]],
        colWidths=[col_width, 35, col_width],
        style=TableStyle([
            ('FONTSIZE', (0, 0), (2, 0), FONTSIZE),
            ('LINEABOVE', (0, 0), (0, 0), 1.2, colors.black),
            ('LINEABOVE', (2, 0), (2, 0), 1.2, colors.black),
            ('VALIGN', (0, 0), (2, 0), 'TOP'),
        ]),
    )

    story = [
        header, Spacer(1, 15 * mm),
        sales_heading, sales, Spacer(1, 10 * mm),
        items_heading, items, Spacer(1, 30 * mm),
        signatures,
    ]
    doc.build(story)

    _buffer.seek(0)
    stored_name = default_storage.save(session.get_new_report_path(), ContentFile(_buffer.read()))
    return stored_name
コード例 #18
0
def cedula_hallazgo(documento):
    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    output = PdfFileWriter()
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Cedula_de_Hallazgo.pdf'

    buffer = StringIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=50,
                            bottomMargin=100)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontSize=8))
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              fontSize=8))

    Story = []

    I = Image(os.path.join(settings.BASE_DIR, 'static', 'img', 'logo.png'))
    I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
    I.drawWidth = 1.25 * inch
    data = [[I, '', '', '', '', ''], ['SUJETO PASIVO:', '', '', '', '', ''],
            ['MATERIA:', '', '', '', '', '']]
    data[0][2] = Paragraph(
        u'''<b>CEDULA DE HALLAZGOS<br/>
                            Contribución Especial del 1% por la Presentación de<br/>
                            Servicios Turísticos</b>''', styles["Center"])
    data[0][4] = documento.codigo
    data[1][1] = documento.pst.nombre_o_razon()
    data[1][3] = 'RIF: ' + documento.pst.rif
    data[2][1] = documento.hallazgos_materia
    data[2][3] = 'PERIODO: ' + documento.fecha_notificacion.strftime(
        "%d/%m/%Y")
    w = [80, 30, 90, 90, 80, 80]
    Story.append(
        Table(data,
              colWidths=w,
              style=[('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                     ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                     ('FONTSIZE', (0, 0), (-1, -1), 8),
                     ('SPAN', (0, 0), (1, 0)), ('SPAN', (2, 0), (3, 0)),
                     ('SPAN', (4, 0), (5, 0)), ('SPAN', (1, 1), (2, 1)),
                     ('SPAN', (1, 2), (2, 2)), ('SPAN', (3, 1), (5, 1)),
                     ('SPAN', (3, 2), (5, 2))]))
    Story.append(Spacer(1, 12))

    data = [['CONDICIÓN', 'CRITERIO', 'EFECTO', 'EVIDENCIA'], ['', '', '', ''],
            ['', '', '', '']]
    try:
        data[2][0] = Paragraph(documento.hallazgos_condicion,
                               styles["Justify"])
        data[2][1] = Paragraph(documento.hallazgos_criterio, styles["Justify"])
        data[2][2] = Paragraph(documento.hallazgos_efecto, styles["Justify"])
        data[2][3] = Paragraph(documento.hallazgos_evidencia,
                               styles["Justify"])
    except:
        pass
    Story.append(
        Table(data,
              colWidths=[95, 170, 81, 105],
              style=[
                  ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                  ('GRID', (0, 2), (-1, 2), 0.25, colors.black),
                  ('FONTSIZE', (0, 0), (-1, -1), 8),
                  ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                  ('VALIGN', (0, 2), (-1, 2), 'TOP'),
              ]))
    Story.append(Spacer(1, 12))

    ptext = 'Observaciones: <u>%s</u>' % documento.observaciones
    Story.append(Paragraph(ptext, styles['Normal']))
    Story.append(Spacer(1, 12))

    Story.append(
        Paragraph('Fiscal Actuante: %s' % gerente.get_full_name(),
                  styles['Normal']))
    Story.append(
        Paragraph('Supervisor: %s' % supervisor.get_full_name(),
                  styles['Normal']))

    doc.build(Story)

    watermark = PdfFileReader(buffer)
    output.addPage(watermark.getPage(0))
    output.write(response)
    return response
コード例 #19
0
ファイル: pcp2pdf_stats.py プロジェクト: mbaldessari/pcpstats
    def output(self, output_file='output.pdf'):
        sys.stdout.write('Parsing archive: ')
        sys.stdout.flush()
        rate_converted = self.parse()
        print()
        doc = PcpDocTemplate(output_file, pagesize=landscape(A4))
        hostname = self.pcparchive.get_hostname()
        self.story.append(Paragraph('%s' % hostname, doc.centered))
        self.story.append(Spacer(1, 0.05 * inch))
        self.story.append(
            Paragraph('%s' % (" ".join(self.args)), doc.small_centered))
        self._do_heading('Table of contents', doc.centered_index)
        self.story.append(doc.toc)
        self.story.append(PageBreak())

        # Prepare the full list of graphs that will be drawn
        # Start with any custom graphs if they exist and
        # proceed with the remaining ones. Split the metrics
        # that have string values into a separate array
        # all_graphs = [(label, fname, (m0, m1, .., mN), text), ...]
        self.all_graphs = []
        string_metrics = []
        for graph in self.custom_graphs:
            (label, metrics) = graph
            fname = self._graph_filename(label)
            text = None
            custom_metrics = []
            for metric in metrics:  # verify that the custom graph's metrics actually exist
                if metric in self.all_data:
                    custom_metrics.append(metric)

            if len(custom_metrics) > 0:
                if isinstance(metrics,
                              str) and metrics in self.pcphelp.help_text:
                    text = '<strong>%s</strong>: %s' % (
                        metrics, self.pcphelp.help_text[metrics])
                self.all_graphs.append((label, fname, custom_metrics, text))

        for metric in sorted(self.all_data):
            if self.is_string_metric(metric):
                string_metrics.append(metric)
            else:
                fname = self._graph_filename([metric])
                units = self.pcparchive.get_metric_info(metric)[2]
                text = '%s' % units
                if isinstance(metric,
                              str) and metric in self.pcphelp.help_text:
                    text = '<strong>%s</strong>: %s (%s)' % (
                        metric, self.pcphelp.help_text[metric], units)
                if rate_converted[metric] != False:
                    text = text + ' - <em>%s</em>' % 'rate converted'
                self.all_graphs.append((metric, fname, [metric], text))

        done_metrics = []
        # This list contains the metrics that contained data
        print('Creating graphs: ', end='')
        if THREADED:
            pool = multiprocessing.Pool(NR_CPUS)
            l = zip(repeat(self), self.all_graphs)
            metrics_rets = pool.map(graph_wrapper, l)
            (metrics, rets) = zip(*metrics_rets)
            done_metrics = [metric for (metric, ret) in metrics_rets if ret]
        else:
            for graph in self.all_graphs:
                (label, fname, metrics, text) = graph
                if self.create_graph(fname, label, metrics):
                    progress_callback(True)
                    done_metrics.append(graph)
                else:
                    # Graphs had all zero values
                    progress_callback(False)

        print()
        # Build the string metrics table. It only prints
        # a value if it changed over time
        data = [('Metric', 'Timestamp', 'Value')]
        for metric in string_metrics:
            last_value = None
            for indom in self.all_data[metric]:
                timestamps = self.all_data[metric][indom][0]
                values = self.all_data[metric][indom][1]
                for (ts, v) in zip(timestamps, values):
                    if last_value != v:
                        text = ellipsize(v)
                        data.append((metric, '%s' % ts, text))
                        last_value = v

        if len(data) > 1:
            self._do_heading('String metrics', doc.h1)
            self.story.append(Spacer(1, 0.2 * inch))
            table = Table(data)
            table.setStyle(tablestyle)
            self.story.append(table)
            self.story.append(PageBreak())

        # At this point all images are created let's build the pdf
        print("Building pdf: ", end='')
        # Add the graphs to the pdf
        last_category = ''
        for graph in done_metrics:
            (label, fname, metrics, text) = graph
            category = self.get_category(metrics)
            if last_category != category:
                self._do_heading(category, doc.h1)
                last_category = category

            self._do_heading(label, doc.h2_invisible)
            self.story.append(
                Image(fname,
                      width=GRAPH_SIZE[0] * inch,
                      height=GRAPH_SIZE[1] * inch))
            if text:
                self.story.append(Paragraph(text, doc.normal))
            self.story.append(PageBreak())
            sys.stdout.write('.')
            sys.stdout.flush()

        doc.multiBuild(self.story)
        print()
        print("Done building: {0}".format(output_file))
        shutil.rmtree(self.tempdir)
        print("Done removing: {0}".format(self.tempdir))
コード例 #20
0
 def _add_some_space(self):
     """
     Adds some blank space after last part.
     """
     self.parts.append(Spacer(self.spacer_width, self.spacer_height))
コード例 #21
0
ファイル: views.py プロジェクト: WestKeeper/diplom
def pdf_report(dataset_filepath: str):
    plt.switch_backend('agg')
    df = pd.read_excel(dataset_filepath)
    df_cols = list(df.columns)
    if 'Курс' in df_cols:
        df['Курс'] = df['Курс'].astype('object')
    if 'Класс' in df_cols:
        df['Класс'] = df['Класс'].astype('object')
    cat_cols = []
    num_cols = []
    for col in df_cols:
        if col in CATEGORY_COLUMNS:
            cat_cols.append(col)
        elif col in NUMERIC_COLUMNS:
            num_cols.append(col)

    df_filename = dataset_filepath.split('/')[-1]
    df_name = ''
    string = df_filename.split('.')[:-1]
    for s in string:
        df_name += s
    pdf_filename = df_name + '_results.pdf'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s"' % pdf_filename

    pdfmetrics.registerFont(TTFont('Times', 'times.ttf', 'UTF-8'))
    pdfmetrics.registerFont(TTFont('Times-Bold', 'timesbd.ttf', 'UTF-8'))
    pdfmetrics.registerFont(TTFont('Times-Italic', 'timesi.ttf', 'UTF-8'))
    pdfmetrics.registerFont(TTFont('Times-BoldItalic', 'timesbi.ttf', 'UTF-8'))

    addMapping('Times', 0, 0, 'Times')  # normal
    addMapping('Times', 0, 1, 'Times-Italic')  # italic
    addMapping('Times', 1, 0, 'Times-Bold')  # bold
    addMapping('Times', 1, 1, 'Times-BoldItalic')  # italic and bold

    doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=40, leftMargin=40, topMargin=20, bottomMargin=40,
                            title='Результаты')
    story = []
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Times', fontSize=11))
    styles.add(ParagraphStyle(name='Justify-Bold', alignment=TA_JUSTIFY, fontName='Times-Bold'))
    bold_style = styles['Justify-Bold']
    normal_style = styles['Justify']
    doc_title = copy.copy(styles["Heading1"])
    doc_title.alignment = TA_LEFT
    doc_title.fontName = 'Times-Bold'
    doc_title.fontSize = 16
    logo = 'static/img/tpu-logo.png'
    im = Image(logo)
    story.append(im)
    story.append(Spacer(1, 10))
    title1 = "Статистика по характеристикам студентов за х семестр у года"
    story.append(Paragraph(title1, doc_title))

    result_table_style = TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Times-Bold', 10),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BACKGROUND', (0, 0), (15, -2), colors.lightgrey),
    ])

    normal_table_style = TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Times', 10),
        ('ALIGN', (0, 0), (0, -1), 'CENTRE'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
    ])

    data = df_describe(df)
    table = Table(data)
    table.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Times', 10),
        ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
    ]))
    story.append(table)
    story.append(Spacer(1, 10))

    for col in df_cols:
        hist = df_hist(df, col, df_name)
        him = Image(hist)  # , 70 * mm, 40 * mm
        story.append(him)
        story.append(Spacer(1, 10))
        if col in num_cols:
            boxplot = df_boxplot(df, col, df_name)
            bim = Image(boxplot)  # , 70 * mm, 40 * mm
            story.append(bim)
            story.append(Spacer(1, 10))


    title2 = "Поиск скрытых зависимостей"
    story.append(Paragraph(title2, doc_title))
    doc_title.fontSize = 12

    for cat_col in cat_cols:
        title3 = cat_col
        story.append(Paragraph(title3, doc_title))

        catplot = df_catplot(df, cat_col, df_name)
        cim = Image(catplot)
        story.append(cim)
        story.append(Spacer(1, 10))

        qq_plot = df_qqplot(df, cat_col, df_name)
        qim = Image(qq_plot)
        story.append(qim)
        story.append(Spacer(1, 10))

        stats_str, result = df_hypothises(df, cat_col)
        story.append(Paragraph(stats_str, normal_style))
        for res in result:
            story.append(Paragraph(res, normal_style))
        story.append(Spacer(1, 10))

    doc.build(story, onFirstPage=addPageNumber, onLaterPages=addPageNumber)
    return response
コード例 #22
0
ファイル: __init__.py プロジェクト: agdsn/pycroft
def generate_user_sheet(new_user,
                        wifi,
                        user=None,
                        user_id=None,
                        plain_user_password=None,
                        generation_purpose='',
                        plain_wifi_password=''):
    """Create a new datasheet for the given user.
    This usersheet can hold information about a user or about the wifi credentials of a user.

    :param bool new_user: Generate a page for a new created user
    :param bool wifi: Generate a page with the wifi credantials

    Necessary in every case:
    :param User user: A pycroft user
    :param str user_id: The user's ID.  It has to be given extra,
        because the user_id is not appearent given the ORM object
        itself; encoding is done in the library.

    Only necessary if new_user=True:
    :param str plain_user_password: The password

    Only necessary if wifi=True:
    :param str plain_wifi_password: The password for wifi
    """
    # Anlegen des PDF Dokuments, Seitengröße DIN A4 Hochformat)
    buf = BytesIO()
    pdf = SimpleDocTemplate(buf,
                            pagesize=A4,
                            rightMargin=1.5 * cm,
                            leftMargin=1.5 * cm,
                            topMargin=0.5 * cm,
                            bottomMargin=0.5 * cm)
    style = getStyleSheet()
    story = []

    PAGE_WIDTH = defaultPageSize[0]
    PAGE_HEIGHT = defaultPageSize[1]

    # HEADER
    im_web = Image(ASSETS_WEB_FILENAME, 0.4 * cm, 0.4 * cm)
    im_house = Image(ASSETS_HOUSE_FILENAME, 0.4 * cm, 0.4 * cm)
    im_email = Image(ASSETS_EMAIL_FILENAME, 0.4 * cm, 0.4 * cm)
    im_fb = Image(ASSETS_FACEBOOK_FILENAME, 0.4 * cm, 0.4 * cm)
    im_t = Image(ASSETS_TWITTER_FILENAME, 0.4 * cm, 0.4 * cm)
    im_logo = Image(ASSETS_LOGO_FILENAME, 3.472 * cm, 1 * cm)

    # add a page with the user data
    if new_user is True:
        if user.room:
            shortinfo = Paragraph(
                '{dorm}<br/>{name}<br/>{level}/{room}'.format(
                    dorm=str(user.room.building.short_name),
                    name=user.name,
                    level=str(user.room.level),
                    room=str(user.room.number)), style['RightText'])
        else:
            shortinfo = Paragraph('{name}'.format(name=user.name),
                                  style['RightText'])

        data = [[im_web, 'https://agdsn.de', im_t, '/ag_dsn'],
                [
                    im_email, '*****@*****.**', im_fb,
                    '/DresdnerStudentenNetz'
                ]]
        social = Table(data,
                       colWidths=[0.5 * cm, 3.5 * cm, 0.5 * cm],
                       rowHeights=[0.5 * cm] * 2)

        data = [[im_logo, social, shortinfo]]
        t = Table(data,
                  colWidths=[3.972 * cm, 9.5 * cm, 4 * cm],
                  style=[
                      ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                  ])
        story.append(t)

        story.append(
            HRFlowable(width="100%",
                       thickness=1,
                       color=black,
                       spaceBefore=0.0 * cm,
                       spaceAfter=0.5 * cm))

        welcome = Paragraph(
            f'''Welcome as a member of the AG DSN, {user.name}!
    We are proud to announce that your network access has been activated. If you encounter any problems, drop us a mail or visit us during our office hours. You can find contact information below on this page.''',
            style['BodyText'])

        return_notice = Paragraph(
            '''<font size="9pt">Nicht nachsenden!</font>''', style['Normal'])
        sender = Paragraph(
            '''<font size="9pt">AG DSN • Support • Wundtstraße 5 • 01217 Dresden</font>''',
            style['Normal'])
        address = f"{user.name}\n{user.address:long}"
        data = [[None, None], [return_notice, None], [sender, None],
                [address, welcome]]
        addressTable = Table(data,
                             colWidths=[9 * cm, pdf.width - 9 * cm],
                             rowHeights=[1 * cm, 0.3 * cm, 0.8 * cm, 3 * cm],
                             style=[
                                 ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                             ])
        story.append(addressTable)

        story.append(
            HRFlowable(width="100%",
                       thickness=3,
                       color=black,
                       spaceBefore=0.4 * cm,
                       spaceAfter=0.4 * cm))

        macs = []
        for user_host in user.hosts:
            for ip in user_host.ips:
                macs.append(ip.interface.mac)

        email = user.email_internal
        email_redirect = ""
        if user.email is not None:
            email_redirect = f"Your mails are redirected to: {user.email}"
        need_explicit_address = not user.room or user.room.address != user.address
        data = [['Name:', user.name, 'User-ID:', user_id],
                ['Username:'******'MAC-Address:', ', '.join(macs)],
                [
                    'Password:'******'Dorm Location:' if need_explicit_address else 'Location:',
                    str(user.room) if user.room else ""
                ], ['E-Mail:', email, "", ""], ["", email_redirect, "", ""]]
        if need_explicit_address:
            data.append(['Address:', user.address])
        t = Table(
            data,
            style=[
                ('FONTNAME', (1, 2), (1, 2), 'Courier'),
                ('FONTSIZE', (1, 4), (1, 4), 8),
            ],
            colWidths=[pdf.width * 0.15, pdf.width * 0.34] * 2,
        )

        story.append(t)
        story.append(
            HRFlowable(width="100%",
                       thickness=3,
                       color=black,
                       spaceBefore=0.0 * cm,
                       spaceAfter=0.4 * cm))

        # offices
        im_web = Image(ASSETS_WEB_FILENAME, 0.4 * cm, 0.4 * cm)
        im_house = Image(ASSETS_HOUSE_FILENAME, 0.4 * cm, 0.4 * cm)
        im_email = Image(ASSETS_EMAIL_FILENAME, 0.4 * cm, 0.4 * cm)
        im_fb = Image(ASSETS_FACEBOOK_FILENAME, 0.4 * cm, 0.4 * cm)
        im_t = Image(ASSETS_TWITTER_FILENAME, 0.4 * cm, 0.4 * cm)
        data = [[
            '', im_house, 'Wundtstraße 5', im_house, 'Hochschulstr. 50',
            im_house, 'Borsbergstr. 34'
        ], ['', '', 'Doorbell 0100', '', 'Ground floor', '', '7th floor'],
                [
                    '', '', '01217 Dresden', '', '01069 Dresden', '',
                    '01309 Dresden'
                ], ['', '', '', '', '', '', ''],
                [
                    'Office hours:', '', 'Mon, 7pm - 8pm', '',
                    'Mon, 7pm - 7.30pm', '', 'Mon, 8pm - 9pm'
                ],
                [
                    '', '', 'Thu, 7pm - 8pm', '', 'Thu, 7pm - 7.30pm', '',
                    'Thu, 8pm - 9pm'
                ]]

        rowHeight = 0.4 * cm
        t = Table(data,
                  colWidths=[
                      2.5 * cm, 0.5 * cm, 3.5 * cm, 0.5 * cm, 3.5 * cm,
                      0.5 * cm, 3.5 * cm
                  ],
                  rowHeights=[
                      rowHeight, rowHeight, rowHeight, rowHeight, rowHeight,
                      rowHeight
                  ],
                  hAlign='CENTER')
        story.append(t)

        story.append(
            Paragraph('''<b>Interested in our work?</b>
                    In the podcast MultiCast you can hear about the latest developments and
                    our day-to-day work in the students network: https://podcast.agdsn.de/''', \
                      style['JustifyText']))

        story.append(
            Paragraph(
                '''<b>Join us:</b>\nThe student network was created and is run by students like yourself. If you are interested in our work don’t
            hesitate to visit us at our office. There are many ways of contribution to our cause without the need of being a
            computer science engineer. Just to mention some possible contributions: Administration and finances, network
            maintenance, software development and many more. Besides, you can add some extra extracurricular
            activity to your CV and have the opportunity to see and work with usually hidden technology. We would be
            happy to welcome you with us. Be our guest at our office hours.''',
                style['JustifyText']))

        story.append(
            HRFlowable(width="100%",
                       thickness=3,
                       color=black,
                       spaceBefore=0.3 * cm,
                       spaceAfter=0.3 * cm))

        # Payment details
        contribution = 500  # monthly membership contribution in EUR
        story.append(
            Paragraph(
                '''<b>Payment details:</b> As a member, you have to transfer a monthly contribution of {:1.2f}€ to our bank account.
            Paying cash is not possible. The contribution is due at the end of each month. You can pay as much in advance as you want, we will simply subtract
            the monthly contribution at the end of each month. We recommend that you pay at the beginning of each semester in advance, meaning you transact
            six monthly contributions at once.'''.format(contribution / 100),
                style['JustifyText']))

        bank = config.membership_fee_bank_account

        recipient = 'Studierendenrat TUD - AG DSN'

        if user.room:
            purpose = '{id}, {name}, {dorm} {level} {room}'.format(
                id=user_id,
                name=user.name,
                dorm=str(user.room.building.short_name),
                level=str(user.room.level),
                room=str(user.room.number))
        else:
            purpose = '{id}, {name}'.format(id=user_id, name=user.name)

        amount = contribution / 100
        data = [['Beneficiary:', recipient], ['Bank:', bank.bank],
                ['IBAN:', bank.iban], ['BIC:', bank.bic],
                ['Purpose/Intended use/\nDescription:', purpose],
                ['Amount', f'{amount:1.2f}€']]
        payment_table = Table(data,
                              colWidths=[4 * cm, 4 * cm],
                              style=[
                                  ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                              ])

        qr_size = 4 * cm
        qr_code = qr.QrCodeWidget(
            generate_epc_qr_code(bank, recipient, amount, purpose))
        bounds = qr_code.getBounds()
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        girocode = Drawing(
            qr_size,
            qr_size,
            transform=[qr_size / width, 0, 0, qr_size / height, 0, 0])
        girocode.add(qr_code)

        data = [[payment_table, girocode]]
        t = Table(data,
                  colWidths=[13 * cm, 4 * cm],
                  style=[
                      ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'),
                  ])
        story.append(t)

        story.append(
            Paragraph(
                '<i>Scan the QR-Code with your banking app to import the payment details.</i>',
                style['CenterText']))

        if generation_purpose:
            generation_purpose = f' ({generation_purpose})'
        story.append(
            Paragraph(
                '<i>Generated on {date}{purpose}</i>'.format(
                    date=datetime.date.today(), purpose=generation_purpose),
                ParagraphStyle(name='SmallRightText',
                               parent=style['Normal'],
                               alignment=TA_RIGHT,
                               fontSize=8,
                               spaceBefore=10,
                               spaceAfter=0)))

    if new_user is True and wifi is True:
        story.append(PageBreak())

    if wifi is True:
        # add a page with the wifi credentials
        if user.room:
            shortinfo = Paragraph(
                '{dorm}<br/>{name}<br/>{level}/{room}'.format(
                    dorm=str(user.room.building.short_name),
                    name=user.name,
                    level=str(user.room.level),
                    room=str(user.room.number)), style['RightText'])
        else:
            shortinfo = Paragraph('{name}'.format(name=user.name),
                                  style['RightText'])

        data = [[im_web, 'https://agdsn.de', im_t, '/ag_dsn'],
                [
                    im_email, '*****@*****.**', im_fb,
                    '/DresdnerStudentenNetz'
                ]]
        social = Table(data,
                       colWidths=[0.5 * cm, 3.5 * cm, 0.5 * cm],
                       rowHeights=[0.5 * cm] * 2)

        data = [[im_logo, social, shortinfo]]
        t = Table(data,
                  colWidths=[3.972 * cm, 9.5 * cm, 4 * cm],
                  style=[
                      ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                  ])
        story.append(t)
        ######################

        story.append(
            HRFlowable(width="100%",
                       thickness=1,
                       color=black,
                       spaceBefore=0.0 * cm,
                       spaceAfter=0.8 * cm))

        welcome = Paragraph(
            "Hello {},<br/>"
            "In some dormitories we're providing Wi-Fi as an adition to the wired connection. "
            "All of our members can use this Wi-Fi in all of our dormitories, independently "
            "from their residence. "
            " "
            "If you spot any coverage problems, it would be nice if you could inform us "
            "on [email protected]. ".format(user.name), style['BodyText'])

        return_notice = Paragraph(
            '''<font size="9pt">Nicht nachsenden!</font>''', style['Normal'])
        sender = Paragraph(
            '''<font size="9pt">AG DSN • Support • Wundtstraße 5 • 01217 Dresden</font>''',
            style['Normal'])
        address = f"{user.name}\n{user.address:long}"
        data = [[None, None], [return_notice, welcome], [sender, None],
                [address, None]]
        addressTable = Table(data,
                             colWidths=[9 * cm, pdf.width - 9 * cm],
                             rowHeights=[1 * cm, 0.3 * cm, 0.8 * cm, 3 * cm],
                             style=[
                                 ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                             ])
        story.append(addressTable)

        story.append(
            Paragraph(
                'You can find instructions to connect, further information and data protection notices at: '
                'https://agdsn.de/sipa/pages/service/wlan (Scan the QR-Code to visit the page conveniently.) '
                'There you can download configuration assistants for all popular plattforms.',
                style['BodyText']))

        story.append(
            Paragraph(
                'We would really like, if you try our wifi. '
                'If you have any questions, feedback or problems, please come to our office or write to us.',
                style['BodyText']))

        data = [
            ['SSID:', 'agdsn'], ['Outer authentication:', 'TTLS'],
            ['Inner authentication:', 'PAP'],
            [
                'CA certificate:',
                'Use system certificate (when unavailable download\nfrom our website)'
            ], ['Domain:', 'radius.agdsn.de'],
            ['Anonymous identity:', '*****@*****.**'],
            ['Username:'******'Password:'******'VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                     ('FONTNAME', (1, 7), (1, 7), 'Courier'),
                                 ])

        qr_size = 4 * cm
        qr_code = qr.QrCodeWidget('https://agdsn.de/sipa/pages/service/wlan')
        bounds = qr_code.getBounds()
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        qrcode = Drawing(
            qr_size,
            qr_size,
            transform=[qr_size / width, 0, 0, qr_size / height, 0, 0])
        qrcode.add(qr_code)

        data = [[credential_table, qrcode]]
        t = Table(data,
                  colWidths=[13 * cm, 4 * cm],
                  style=[
                      ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                  ])
        story.append(t)

        story.append(Paragraph('Best regards,', style['BodyText']))
        story.append(Paragraph('Your AG DSN', style['BodyText']))

        s = Spacer(width=1 * cm, height=6.8 * cm)
        story.append(s)

        story.append(
            HRFlowable(width="100%",
                       thickness=3,
                       color=black,
                       spaceBefore=0.4 * cm,
                       spaceAfter=0.4 * cm))
        # offices
        im_web = Image(ASSETS_WEB_FILENAME, 0.4 * cm, 0.4 * cm)
        im_house = Image(ASSETS_HOUSE_FILENAME, 0.4 * cm, 0.4 * cm)
        im_email = Image(ASSETS_EMAIL_FILENAME, 0.4 * cm, 0.4 * cm)
        im_fb = Image(ASSETS_FACEBOOK_FILENAME, 0.4 * cm, 0.4 * cm)
        im_t = Image(ASSETS_TWITTER_FILENAME, 0.4 * cm, 0.4 * cm)
        data = [[
            '', im_house, 'Wundtstraße 5', im_house, 'Hochschulstr. 50',
            im_house, 'Borsbergstr. 34'
        ], ['', '', 'Doorbell 0100', '', 'Ground floor', '', '7th floor'],
                [
                    '', '', '01217 Dresden', '', '01069 Dresden', '',
                    '01309 Dresden'
                ], ['', '', '', '', '', '', ''],
                [
                    'Office hours:', '', 'Mon, 7pm - 8pm', '',
                    'Mon, 7pm - 7.30pm', '', 'Mon, 8pm - 9pm'
                ],
                [
                    '', '', 'Thu, 7pm - 8pm', '', 'Thu, 7pm - 7.30pm', '',
                    'Thu, 8pm - 9pm'
                ]]

        rowHeight = 0.4 * cm
        t = Table(data,
                  colWidths=[
                      2.5 * cm, 0.5 * cm, 3.5 * cm, 0.5 * cm, 3.5 * cm,
                      0.5 * cm, 3.5 * cm
                  ],
                  rowHeights=[
                      rowHeight, rowHeight, rowHeight, rowHeight, rowHeight,
                      rowHeight
                  ],
                  hAlign='CENTER')
        story.append(t)

        story.append(
            Paragraph(
                '<i>Generated on {date}</i>'.format(
                    date=datetime.date.today(), ),
                ParagraphStyle(name='SmallRightText',
                               parent=style['Normal'],
                               alignment=TA_RIGHT,
                               fontSize=8,
                               spaceBefore=15)))

    # PDF generieren und speichern
    pdf.build(story)

    return buf.getvalue()
コード例 #23
0
def _create_approval_cols(approval_buffer, approval, proposal, copied_to_permit, user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame], onPage=_create_approval_header)

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

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

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])
    box_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('BOX', (0,0), (-1,-1), 0.25, black), ('INNERGRID', (0,0), (-1,-1), 0.25, black), ('ALIGN', (0, 0), (-1, -1), 'RIGHT')])

    elements = []

    #Organization details

    address = proposal.applicant_address
    # address = proposal.applicant_address
    if proposal.org_applicant:
        try:
            email = proposal.org_applicant.organisation.organisation_set.all().first().contacts.all().first().email
        except:
            raise ValidationError('There is no contact for Organisation. Please create an Organisation contact')
    else:
        email= proposal.submitter.email
    #elements.append(Paragraph(email,styles['BoldLeft']))
    elements.append(Paragraph('CONSERVATION AND LAND MANAGEMENT REGULATIONS 2002 (PART 7)', styles['ItalicCenter']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('COMMERCIAL OPERATIONS LICENCE', styles['InfoTitleVeryLargeCenter']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements.append(Paragraph('The Chief Executive Officer (CEO) of the Department of Biodiversity, Conservation and Attractions hereby grants a commercial operations licence to enter upon and conduct activities within the parks/reserves listed in Schedule 1 of this licence to:', styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # delegation holds the Licence number and applicant name in table format.
    delegation = []
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft'])],
                              [Paragraph(_format_name(approval.applicant),
                                         styles['Left'])]]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=approval_table_style))

    if approval.current_proposal.org_applicant and approval.current_proposal.org_applicant.organisation.trading_name:
        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        delegation.append(Table([[[Paragraph('Trading Name:', styles['BoldLeft'])],
                                  [Paragraph(_format_name(approval.current_proposal.org_applicant.organisation.trading_name),
                                             styles['Left'])]]],
                                colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                                style=approval_table_style))


    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Table([[[Paragraph('Licence Number:', styles['BoldLeft'])],
                              [Paragraph(approval.lodgement_number,
                                         styles['Left'])]]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=approval_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))


    elements.append(KeepTogether(delegation))

    elements.append(Paragraph('Commencing on the {} and expiring on {}.'.format(approval.start_date.strftime(DATE_FORMAT2), approval.expiry_date.strftime(DATE_FORMAT2)),styles['BoldLeft']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('CONDITIONS', styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    list_of_bullets= []
    list_of_bullets.append('This Commercial Operations Licence is subject to the provisions of the <i>Conservation and Land Management Act 1984</i> and all subsidiary legislation made under it.')
    list_of_bullets.append('The Licensee must comply with and not contravene the conditions and restrictions set out in the Commercial Operator Handbook as varied from time to time by the CEO.')
    list_of_bullets.append('The Licensee must comply with the conditions contained in any schedule of conditions attached to this Commercial Operations Licence.')

    understandingList = ListFlowable(
            [ListItem(Paragraph(a, styles['Left']), bulletColour='black') for a in list_of_bullets],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
            #bulletFontName=BOLD_FONTNAME
    elements.append(understandingList)

    # proposal requirements
    # requirements = proposal.requirements.all().exclude(is_deleted=True)
    # if requirements.exists():
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph('The following requirements must be satisfied for the licence not to be withdrawn:', styles['BoldLeft']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #     conditionList = ListFlowable(
    #         [Paragraph(a.requirement, styles['Left']) for a in requirements.order_by('order')],
    #         bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
    #     elements.append(conditionList)

    elements += _layout_extracted_fields(approval.extracted_fields)

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements.append(Paragraph('{} {}'.format(user.first_name, user.last_name), styles['Left']))
    if user.position_title:
        elements.append(Paragraph('{}'.format(user.position_title), styles['Left']))
    elements.append(Paragraph('As Delegate of CEO', styles['Left']))
    elements.append(Paragraph('Under Section 133(2) of the CALM Act 1984', styles['Left']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']))

    elements.append(PageBreak())
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    table_data=[[Paragraph('Licence Number', styles['BoldLeft']), Paragraph(_format_name(approval.lodgement_number), styles['Left'])],
                [Paragraph('Commencement Date', styles['BoldLeft']), Paragraph(_format_name(approval.start_date).strftime(DATE_FORMAT), styles['Left'])],    
                [Paragraph('Expiry Date', styles['BoldLeft']), Paragraph(_format_name(approval.expiry_date).strftime(DATE_FORMAT), styles['Left'])]]
    t=Table(table_data, colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=box_table_style)
    elements.append(t)

    # Schedule 1
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('SCHEDULE 1', styles['BoldCenter']))
    elements.append(Paragraph('COMMERCIAL OPERATIONS LICENCE ACTIVITIES', styles['BoldCenter']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    park_data=[]
    for p in approval.current_proposal.selected_parks_activities_pdf:
        #park_data.append([Paragraph(_format_name(p['park']), styles['BoldLeft']),
        #                     [Paragraph(a, styles['Left']) for a in p['activities']]])
        activities_str=[]
        for ac in p['activities']:
            activities_str.append(ac.encode('UTF-8'))
        activities_str=str(activities_str).strip('[]').replace('\'', '')
        park_data.append([Paragraph(_format_name(p['park']), styles['BoldLeft']),
                              Paragraph(activities_str, styles['Left'])])
    if park_data:
        t=Table(park_data, colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=box_table_style)
    elements.append(t)

    # Schedule 2
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('SCHEDULE 2', styles['BoldCenter']))
    elements.append(Paragraph('COMMERCIAL OPERATIONS LICENCE LAND ACCESS TYPES', styles['BoldCenter']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    park_data=[]
    for p in approval.current_proposal.selected_parks_access_types_pdf:
        access_types_str=[]
        for ac in p['access_types']:
            access_types_str.append(ac.encode('UTF-8'))
        access_types_str = ', '.join(access_types_str).replace('\'', '')
        park_data.append([Paragraph(_format_name(p['park']), styles['BoldLeft']),
                              Paragraph(access_types_str, styles['Left'])])
    if park_data:
        t=Table(park_data, colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=box_table_style)
    elements.append(t)

    # Schedule 3
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('SCHEDULE 3', styles['BoldCenter']))
    elements.append(Paragraph('COMMERCIAL OPERATIONS LICENCE CONDITIONS', styles['BoldCenter']))
    requirements = proposal.requirements.all().exclude(is_deleted=True)
    if requirements.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #elements.append(Paragraph('The following requirements must be satisfied for the licence not to be withdrawn:', styles['BoldLeft']))
        #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable(
            [Paragraph(a.requirement, styles['Left']) for a in requirements.order_by('order')],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    doc.build(elements)

    return approval_buffer
コード例 #24
0
    def genTaskPDF(self, hold_buy_day, hold_sell_day, hold_buy_week, hold_sell_week, other_buy_week, other_sell_week, method):
        styles = getSampleStyleSheet()
        normalStyle = copy.deepcopy(styles['Normal'])
        normalStyle.fontName = 'SimSun'
        story = []
        story.append(
            Graphs.draw_title('kd_macd_future_%s' % datetime.datetime.now().strftime('%Y%m%d')))
        story.append(Spacer(0, 0.5 * cm))

        story.append(Paragraph('在持仓日频KD金叉: ', normalStyle))
        story.append(Spacer(0, 0.2 * cm))
        data = [tuple(hold_buy_day.columns)] + [tuple(x.to_dict().values()) for idx, x in hold_buy_day.iterrows()]
        story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                         col_width=[80] + [70] * (len(hold_buy_day.columns) - 1)))
        story.append(Spacer(0, 0.5 * cm))

        story.append(Paragraph('在持仓日频KD死叉: ', normalStyle))
        story.append(Spacer(0, 0.2 * cm))
        data = [tuple(hold_sell_day.columns)] + [tuple(x.to_dict().values()) for idx, x in hold_sell_day.iterrows()]
        story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                       col_width=[80] + [70] * (len(hold_sell_day.columns) - 1)))
        story.append(Spacer(0, 0.5 * cm))

        if method == 1:
            story.append(Paragraph('在持仓周频KD金叉: ', normalStyle))
            story.append(Spacer(0, 0.2 * cm))
            data = [tuple(hold_buy_week.columns)] + [tuple(x.to_dict().values()) for idx, x in hold_buy_week.iterrows()]
            story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                           col_width=[80] + [70] * (len(hold_buy_week.columns) - 1)))
            story.append(Spacer(0, 0.5 * cm))

            story.append(Paragraph('在持仓周频KD死叉: ', normalStyle))
            story.append(Spacer(0, 0.2 * cm))
            data = [tuple(hold_sell_week.columns)] + [tuple(x.to_dict().values()) for idx, x in hold_sell_week.iterrows()]
            story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                           col_width=[80] + [70] * (len(hold_sell_week.columns) - 1)))
            story.append(Spacer(0, 0.5 * cm))

            story.append(Paragraph('非在持仓周频KD金叉: ', normalStyle))
            story.append(Spacer(0, 0.2 * cm))
            data = [tuple(other_buy_week.columns)] + [tuple(x.to_dict().values()) for idx, x in other_buy_week.iterrows()]
            story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                           col_width=[80] + [70] * (len(other_buy_week.columns) - 1)))
            story.append(Spacer(0, 0.5 * cm))

            story.append(Paragraph('非在持仓周频KD死叉: ', normalStyle))
            story.append(Spacer(0, 0.2 * cm))
            data = [tuple(other_sell_week.columns)] + [tuple(x.to_dict().values()) for idx, x in
                                                      other_sell_week.iterrows()]
            story.append(Graphs.draw_table(*data, ALIGN='LEFT', VALIGN='RIGHT',
                                           col_width=[80] + [70] * (len(other_sell_week.columns) - 1)))
            story.append(Spacer(0, 0.5 * cm))

        doc = SimpleDocTemplate(self.file_path + self.filename + ".pdf", pagesize=letter)
        doc.build(story)
コード例 #25
0
def _create_renewal(renewal_buffer, approval, proposal):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame], onPage=_create_approval_header)

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

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

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []


    #title = approval.title.encode('UTF-8')
    title=''
    # additional information
    '''if approval.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))
        elements += _layout_paragraphs(approval.additional_information)'''

    # delegation holds the dates, approvale and issuer details.
    delegation = []
    # proponent details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #address = proposal.applicant.organisation.postal_address
    address = proposal.applicant_address
    address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
                          Paragraph(address.line3, styles['Left']),
                          Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
                          Paragraph(address.country.name, styles['Left'])]
    # if proposal.org_applicant:
    #     address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
    #                       Paragraph(address.line3, styles['Left']),
    #                       Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
    #                       Paragraph(address.country.name, styles['Left'])]
    # else:
    #     address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
    #                       Paragraph(address.line3, styles['Left']),
    #                       Paragraph('%s %s' % (address.state, address.postcode), styles['Left']),
    #                       Paragraph(address.country.name, styles['Left'])]
    delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
                              [Paragraph(_format_name(approval.applicant),
                                         styles['Left'])] + address_paragraphs]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=approval_table_style))

    expiry_date = approval.expiry_date.strftime(DATE_FORMAT)
    full_name = proposal.submitter.get_full_name()

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Dear {} '.format(full_name), styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # delegation.append(Paragraph('This is a reminder that your approval: ', styles['Left']))

    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # title_with_number = '{} - {}'.format(approval.lodgement_number, title)

    # delegation.append(Paragraph(title_with_number, styles['InfoTitleLargeLeft']))

    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # delegation.append(Paragraph('is due to expire on {}'.format(expiry_date), styles['Left']))

    delegation.append(Paragraph('This is a reminder that your Commercial Operations licence {} expires on {}. '.format(approval.lodgement_number, expiry_date), styles['BoldLeft']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('It is important you apply to renew your licence now so that we can process it before your current licence expires.'
                                'If you would like to continue operating within WA\'s national parks and other conservation reserves you need a licence under the Conservation and Land Management Regulations 2002.', styles['Left']))
    #delegation.append(Paragraph('If you would like to continue operating within WA\'s national parks and other conservation reserves you need a licence under the Conservation and Land Management Regulations 2002.'
    #                            , styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('As a reminder, the Commercial Operator Handbook (2019) outlines the conditions of your licence.'
        'The handbook is available online at the {} website:'.format(settings.DEP_NAME), styles['Left']))
    #delegation.append(Paragraph('The handbook is available online at the {} website: .'.format(settings.DEP_NAME), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('{}'.format(settings.COLS_HANDBOOK_URL), styles['WebAddress']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Please make sure you have access to this handbook, either in hardcopy or online, when operating within WA\'s national parks and conservation reserves.', styles['Left']))
    #delegation.append(Paragraph('', styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('If you have any questions about how to renew your licence please call Licencing Officer on {} or email [email protected].'.format(settings.DEP_PHONE), styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Yours sincerely ', styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #delegation.append(Paragraph('DIRECTOR GENERAL', styles['Left']))
    delegation.append(Paragraph('{}'.format(settings.DEP_NAME), styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return renewal_buffer
コード例 #26
0
def generate_statistics_pdf(activities=None,
                            start_date=None,
                            all_years=False,
                            year=None):
    ''' Accepts EighthActivity objects and outputs a PDF file. '''
    if activities is None:
        activities = EighthActivity.objects.all().order_by("name")
    if year is None:
        year = current_school_year()

    if not isinstance(activities, list):
        activities = activities.prefetch_related("rooms").prefetch_related(
            "sponsors")

    pdf_buffer = BytesIO()

    h_margin = 1 * inch
    v_margin = 0.5 * inch
    doc = SimpleDocTemplate(pdf_buffer,
                            pagesize=letter,
                            rightMargin=h_margin,
                            leftMargin=h_margin,
                            topMargin=v_margin,
                            bottomMargin=v_margin)

    elements = []

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="Indent", leftIndent=15))

    empty_activities = []

    for act in activities:
        lelements = []
        relements = []
        act_stats = calculate_statistics(act,
                                         start_date=start_date,
                                         all_years=all_years,
                                         year=year)
        if act_stats["total_blocks"] == 0:
            empty_activities.append(act.name)
            continue
        elements.append(Paragraph(act.name, styles["Title"]))
        sponsor_str = (", ".join([x.name for x in act.sponsors.all()
                                  ])) if act.sponsors.count() > 0 else "None"
        lelements.append(
            Paragraph("<b>Default Sponsors:</b> " + sponsor_str,
                      styles["Normal"]))
        lelements.append(Spacer(0, 0.025 * inch))
        room_str = (", ".join([str(x) for x in act.rooms.all()
                               ])) if act.rooms.count() > 0 else "None"
        relements.append(
            Paragraph("<b>Default Rooms:</b> " + room_str, styles["Normal"]))
        relements.append(Spacer(0, 0.025 * inch))

        relements.append(
            Paragraph(
                "<b>Total blocks:</b> {}".format(act_stats["total_blocks"]),
                styles["Normal"]))
        relements.append(
            Paragraph(
                "<b>Scheduled blocks:</b> {}".format(
                    act_stats["scheduled_blocks"]), styles["Indent"]))
        relements.append(
            Paragraph(
                "<b>Empty blocks:</b> {}".format(act_stats["empty_blocks"]),
                styles["Indent"]))
        relements.append(
            Paragraph(
                "<b>Cancelled blocks:</b> {}".format(
                    act_stats["cancelled_blocks"]), styles["Indent"]))

        lelements.append(
            Paragraph(
                "<b>Total signups:</b> {}".format(act_stats["total_signups"]),
                styles["Normal"]))
        lelements.append(
            Paragraph(
                "<b>Average signups per block:</b> {}".format(
                    act_stats["average_signups"]), styles["Indent"]))
        lelements.append(
            Paragraph(
                "<b>Average signups per student:</b> {}".format(
                    act_stats["average_user_signups"]), styles["Indent"]))
        lelements.append(
            Paragraph(
                "<b>Unique students:</b> {}, <b>Capacity:</b> {}".format(
                    act_stats["students"], act_stats["capacity"]),
                styles["Normal"]))

        elements.append(
            Table([[lelements, relements]],
                  style=[('LEFTPADDING', (0, 0), (-1, -1), 0),
                         ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                         ('VALIGN', (0, 0), (-1, -1), 'TOP')]))

        parsed_members = [[x.username, y] for x, y in act_stats["members"]]
        parsed_members = list(chunks(parsed_members, 30))[:3]
        if parsed_members:
            parsed_members = [[["Username", "Signups"]] + x
                              for x in parsed_members]
            parsed_members = [
                Table(x,
                      style=[('FONT', (0, 0), (1, 0), 'Helvetica-Bold'),
                             ('ALIGN', (1, 0), (1, -1), 'RIGHT')])
                for x in parsed_members
            ]
            elements.append(
                Table([parsed_members],
                      style=[('VALIGN', (-1, -1), (-1, -1), 'TOP')]))
            if act_stats["students"] - 90 > 0:
                elements.append(
                    Paragraph(
                        "<b>{}</b> students were not shown on this page. ".
                        format(act_stats["students"] - 90), styles["Normal"]))
        else:
            elements.append(Spacer(0, 0.20 * inch))

        if start_date is not None:
            elements.append(
                Paragraph(
                    "<b>{}</b> block(s) are past the start date and are not included on this page."
                    .format(act_stats["past_start_date"]), styles["Normal"]))
        elements.append(
            Paragraph(
                "<b>{}</b> block(s) not in the {}-{} school year are not included on this page."
                .format(act_stats["old_blocks"], year - 1,
                        year), styles["Normal"]))

        elements.append(PageBreak())

    if empty_activities:
        empty_activities = [
            x[:37] + "..." if len(x) > 40 else x for x in empty_activities
        ]
        empty_activities = [[x] for x in empty_activities]
        empty_activities = list(chunks(empty_activities, 35))
        empty_activities = [[["Activity"]] + x for x in empty_activities]
        empty_activities = [
            Table(x,
                  style=[('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                         ('LEFTPADDING', (0, 0), (-1, -1), 0)])
            for x in empty_activities
        ]
        for i in range(0, len(empty_activities), 2):
            elements.append(
                Paragraph("Empty Activities (Page {})".format(i // 2 + 1),
                          styles["Title"]))
            if all_years:
                elements.append(
                    Paragraph(
                        "The following activities have no 8th period blocks assigned to them.",
                        styles["Normal"]))
            else:
                elements.append(
                    Paragraph(
                        "The following activities have no 8th period blocks assigned to them for the {}-{} school year."
                        .format(year - 1, year), styles["Normal"]))
            elements.append(Spacer(0, 0.10 * inch))
            ea = [empty_activities[i]]
            if i + 1 < len(empty_activities):
                ea.append(empty_activities[i + 1])
            elements.append(
                Table([ea],
                      style=[
                          ('LEFTPADDING', (0, 0), (-1, -1), 0),
                          ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                          ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                      ],
                      hAlign='LEFT'))
            elements.append(PageBreak())

    def first_page(canvas, _):
        if len(activities) == 1:
            canvas.setTitle("{} Statistics".format(activities[0].name))
        else:
            canvas.setTitle("8th Period Activity Statistics")
        canvas.setAuthor("Generated by Ion")

    doc.build(elements, onFirstPage=first_page)

    pdf_buffer.seek(0)

    return pdf_buffer
コード例 #27
0
 def drawTable(self):
     table = ''
     tableheader = []
     if self.DATA_TYPE == 'SSH':
         table = 'sshdata'
         tableheader = ['Ip','Date','User','Location','Attempts']
     elif self.DATA_TYPE == 'UFW':
         table = 'ufwdata'
         tableheader = ['Ip','Date','Location','Attempts']
     elif self.DATA_TYPE == 'APACHE':
         table = 'apachedata'
         tableheader = ['Ip','Date','Location','Attempts']
     filter = {"table" : table, "atribute" : 1}
     
     self.LOGDATA = DataBaseFiles.selectdata(self.conn,filter)
     print(self.LOGDATA)
     ips = {}
     for line in self.LOGDATA:
         if line[1] != '':
             if line[1] not in ips:
                 loc = self.getCountry(line[1])
                 if loc != None and len(loc) > 0:
                     if self.DATA_TYPE == 'SSH':
                         ips[line[1]] = {"attempts" : 1, "location" : loc, "first_seen": line[2], "user": line[3]}
                     elif self.DATA_TYPE == 'UFW':
                         ips[line[1]] = {"attempts" : 1, "location" : loc, "first_seen": line[2]}
                     elif self.DATA_TYPE == 'APACHE':
                         ips[line[1]] = {"attempts" : 1, "location" : loc, "first_seen": line[2]}
                 elif len(loc) == 0:
                     if self.DATA_TYPE == 'SSH':
                         ips[line[1]] = {"attempts" : 1, "location" : 'Not Found', "first_seen": line[2], "user": line[3]}   
                     elif self.DATA_TYPE == 'UFW':
                         ips[line[1]] = {"attempts" : 1, "location" : 'Not Found', "first_seen": line[2]} 
                     elif self.DATA_TYPE == 'APACHE':
                         ips[line[1]] = {"attempts" : 1, "location" : loc, "first_seen": line[2]}
             else:
                 for ip in ips:
                     if line[1] == ip:
                         ips[ip]["attempts"] += 1
     
     self.NORMALIZED_DATA = ips
         
     tabledata= [tableheader]
     for i in ips:
         if self.DATA_TYPE == 'SSH':
             tabledata.append([i, ips[i]["first_seen"], ips[i]["user"], ips[i]["location"], ips[i]["attempts"]])
         elif self.DATA_TYPE == 'UFW':
             tabledata.append([i, ips[i]["first_seen"], ips[i]["location"], ips[i]["attempts"]])
         elif self.DATA_TYPE == 'APACHE':
             tabledata.append([i, ips[i]["first_seen"], ips[i]["location"], ips[i]["attempts"]])
     #print(tabledata)
     t=Table(tabledata,len(tableheader)*[1.5*inch], (len(ips)+1)*[0.4*inch])
     t.setStyle(TableStyle([
     ('ALIGN',(0,(len(ips)+1)),(0,(len(ips)+1)),'CENTER'),
     ('VALIGN',(0,(len(ips)+1)),(0,(len(ips)+1)),'MIDDLE'),
     ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
     ('BOX', (0,0), (-1,-1), 0.25, colors.black),
     ]))
     P = Paragraph('The following ips were found on the {} log file'.format(self.DATA_TYPE),  styles['Normal_CENTER'])
     self.flowables.append(P)
     self.flowables.append(Spacer(20, 0.5*inch))
     self.flowables.append(t)
     self.flowables.append(Spacer(20, 0.5*inch))
コード例 #28
0
    #indico els arxius png que faré servir
    logo_centre = "logo_manyanet.png"
    esquema_dimensions = "esquema_dimensions.png"
    contr_comp = "contribucio_competencies.png"
    formatted_time = time.ctime()

    #creo jo els estils per alinear paragrafs
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='justificat', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name="al_mig", alignment=TA_CENTER))

    #afegeixo el logo del centre
    imatge = Image(logo_centre, 1.7 * inch, 0.5 * inch)
    imatge.hAlign = 'RIGHT'
    Story.append(imatge)
    Story.append(Spacer(1, 25))

    #escric un títol
    text0 = '<font size=16> <b>Qualificació de Matemàtiques</b></font>'
    Story.append(Paragraph(text0, styles["al_mig"]))
    Story.append(Spacer(1, 15))
    #escrc el nom de l'alumne
    text1 = '<font size=12>Alumne(a): <b><big>%s</big></b></font>' % row[0]
    Story.append(Paragraph(text1, styles["al_mig"]))
    Story.append(Spacer(1, 15))

    text8 = '<font size=12> Qualificació final:<font size=15> <b>{}</b></font></font>'.format(
        row[-1])
    Story.append(Paragraph(text8, styles["al_mig"]))
    Story.append(Spacer(0, 25))
コード例 #29
0
def credentials(account):
    """Generate a PDF document containing account credentials."""
    def page_template(canvas, doc):
        canvas.setTitle(_("Personal account information"))
        canvas.setAuthor(account.full_name)
        canvas.setCreator("AccountManager")
        canvas.setFont("IBMPlex", 12)  # choose your font type and font size
        footer = [Paragraph(_("Powered by AccountManager"), styles["Footer"])]
        Frame(0, 0, 21 * cm, 2 * cm).addFromList(footer, canvas)

    rl_config.TTFSearchPath.append(
        str(settings.BASE_DIR) + '/account/reportlab/font')
    pdfmetrics.registerFont(
        TTFont('IBMPlex', 'IBMPlexSansCondensed-Regular.ttf'))

    filename = crypt.get_creds_filename(account)
    buff = BytesIO()
    doc = SimpleDocTemplate(buff, pagesize=A4)
    story = []
    story.append(
        resized_image(crypt.get_document_logo(account.tenant.logo), 6 * cm))
    story.append(Spacer(1, 1 * cm))
    story.append(Paragraph(_("Personal account information"), styles["Title"]))
    story.append(Spacer(1, 1 * cm))
    if account.full_name:
        name = account.full_name
    else:
        name = account.username.split('@')[0]
    story.append(
        Paragraph(
            _("""
Dear %s, this document contains the credentials you will need
to connect to your email account. Learn the content and destroy
the document as soon as possible.
""") % name, styles["Left"]))
    story.append(Spacer(1, 0.4 * cm))
    story.append(Paragraph(_("Web panel:"), styles["Tableheader"]))
    story.append(Spacer(1, 0.2 * cm))
    data = [[_("URL"), account.tenant.weburl],
            [_("username"), str(account.username)],
            [_("password"), account.def_pwd]]
    table = Table(data)
    table.setStyle(
        TableStyle([
            ('TEXTCOLOR', (1, 0), (1, 0), colors.blue),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
            ('FONTNAME', (0, 0), (-1, -1), 'IBMPlex'),
        ]))
    story.append(table)
    story.append(Spacer(1, 0.5 * cm))
    story.append(Spacer(1, 0.2 * cm))
    story.append(
        Paragraph(_("Please change your password!"), styles["Warning"]))

    story.append(Spacer(1, 1 * cm))
    story.append(
        Paragraph(_("PC/Tablet/Smartphone configuration:"),
                  styles["Tableheader"]))
    story.append(Spacer(1, 0.2 * cm))
    data = [
        [_("manual url"), account.tenant.man_url],
        [
            _("IMAP server address (Incoming mail server)"),
            account.tenant.imap_url
        ],
        [_("IMAP server port"), account.tenant.imap_port],
        [_("IMAP connection security"),
         account.tenant.get_imap_sec_display()],
        [
            _("SMTP server address (Outgoing mail server)"),
            account.tenant.smtp_url
        ],
        [_("SMTP server port"), account.tenant.smtp_port],
        [_("SMTP connection security"),
         account.tenant.get_smtp_sec_display()],
    ]
    table = Table(data)
    table.setStyle(
        TableStyle([
            ('TEXTCOLOR', (1, 0), (1, 0), colors.blue),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('FONTNAME', (0, 0), (-1, -1), 'IBMPlex'),
        ]))
    story.append(table)
    story.append(Spacer(1, 0.5 * cm))
    story.append(
        Paragraph(_("Use those settings for your computer, tablet or phone."),
                  styles["Left"]))

    # if conf["custom_message"]:
    #     story.append(Spacer(1, 2 * cm))
    #     story.append(Paragraph("custom_message", "Greeting"))

    doc.build(story, onFirstPage=page_template, onLaterPages=page_template)
    length = len(buff.getvalue())
    buff.seek(0)
    crypt.crypt_and_save_to_file(buff, filename, length)
コード例 #30
0
def get_title_page_story(screenplay):
    """Get Platypus flowables for the title page

    """

    # From Fountain spec:
    # The recommendation is that Title, Credit, Author (or Authors, either
    # is a valid key syntax), and Source will be centered on the page in
    # formatted output. Contact and Draft date would be placed at the lower
    # left.

    def add_lines(story, attribute, style, space_before=0):
        lines = screenplay.get_rich_attribute(attribute)
        if not lines:
            return 0

        if space_before:
            story.append(Spacer(frame_width, space_before))

        total_height = 0
        for line in lines:
            html = line.to_html()
            para = Paragraph(html, style)
            width, height = para.wrap(frame_width, frame_height)
            story.append(para)
            total_height += height
        return space_before + total_height

    title_story = []
    title_height = sum((
        add_lines(title_story, 'Title', title_style),
        add_lines(title_story, 'Credit', centered_style, space_before=12),
        add_lines(title_story, 'Author', centered_style),
        add_lines(title_story, 'Authors', centered_style),
        add_lines(title_story, 'Source', centered_style),
    ))

    lower_story = []
    lower_height = sum((
        add_lines(lower_story, 'Draft date', default_style),
        add_lines(lower_story, 'Contact', contact_style, space_before=12),
        add_lines(lower_story, 'Copyright', centered_style, space_before=12),
    ))

    if not title_story and not lower_story:
        return []

    story = []
    top_space = min(frame_height / 3.0,
                    frame_height - lower_height - title_height)
    if top_space > 0:
        story.append(Spacer(frame_width, top_space))
    story += title_story
    # The minus 6 adds some room for rounding errors and whatnot
    middle_space = frame_height - top_space - title_height - lower_height - 6
    if middle_space > 0:
        story.append(Spacer(frame_width, middle_space))
    story += lower_story

    story.append(platypus.PageBreak())
    return story