コード例 #1
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 = ''
    if approval.title:
        title = approval.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.relevant_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'])
    ]
    delegation.append(
        Table(
            [[
                [
                    Paragraph('Licensee:', styles['BoldLeft']),
                    Paragraph('Address', styles['BoldLeft'])
                ],
                #[Paragraph(_format_name(approval.applicant),
                [Paragraph(approval.relevant_applicant_name, 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(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'Please note that if you have outstanding compliances these are required to be submitted before the approval can be renewed',
            styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'If you have any queries, contact the {} '
            'on {}.'.format(settings.DEP_NAME, 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
コード例 #2
0
    def exec_command(self, spreadsheet_data, args):
        if len(args) < 2:
            print("You must insert output file name")
            return

        print("Generating PDF...")

        # creating doc template and setting up output sheet style
        doc = SimpleDocTemplate(args[1], pagesize=letter)
        pdfmetrics.registerFont(TTFont('Standard', 'src/font.ttf'))
        pdfmetrics.registerFont(TTFont('Bold', 'src/font-bold.ttf'))
        doc.leftMargin = 40
        styles = getSampleStyleSheet()
        style_h1 = ParagraphStyle(name='Heading1',
                                  fontName='Bold',
                                  fontSize=14,
                                  leading=22,
                                  spaceAfter=2)
        style_h2 = ParagraphStyle(name='Heading2',
                                  fontName='Standard',
                                  fontSize=12,
                                  leading=22,
                                  spaceAfter=1)
        space = Spacer(1, 0.20 * inch)
        table_style = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Standard'),
            ('ALIGN', (0, 0), (-2, 0), 'CENTER'),
            ('ALIGN', (0, 0), (0, -5), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ])

        # collect information about room occupancy
        elements = []

        # iterate over any room
        for room_key, room in spreadsheet_data.room_data.data.items():
            print("Sala:",
                  str(room.building_id) + ' - ' + str(room.name) + "\n")
            line = Drawing(520, 10)
            line.add(Line(0, 7, 520, 7))
            elements.append(Paragraph(
                "Sala: " + str(room.building_id) + ' - ' + str(room.name),
                style_h1))
            elements.append(line)

            # for any room check occupancy for any day
            for day in self.tools.days_of_week[0:5]:
                print(self.tools.days_of_week_label[day])
                elements.append(
                    Paragraph(self.tools.days_of_week_label[day], style_h2))

                data_id = id(
                    spreadsheet_data.full_time_first_semester_event_data)
                semester_data = spreadsheet_data.full_time_first_semester_event_data.data

                event_data = [self.table_header]

                # for any day check occupancy in any time block
                if data_id in room.referenced_by:
                    for time_block in self.tools.time_blocks:
                        result = self.get_room_event_by_day(day, time_block,
                                                            room, data_id,
                                                            semester_data)
                        if len(result) == 0:
                            result = [self.tools.time_blocks[time_block], '',
                                      '', '', '']
                        else:
                            for item in result:
                                event_data.append(item)

                if len(event_data) <= 1:
                    event_data = self.get_empty_tab()

                # add new table do sheet
                table = Table(event_data, hAlign='LEFT')
                table.setStyle(table_style)
                elements.append(table)
                elements.append(KeepTogether(Spacer(10, 20)))
            print("------------------------------------------")

        try:
            doc.build(elements)
            print("END, pdf is generated")
        except:
            print("Error while generating pdf, check correct of sheet")
コード例 #3
0
def render_workout_day(day,
                       nr_of_weeks=7,
                       images=False,
                       comments=False,
                       only_table=False):
    '''
    Render a table with reportlab with the contents of the training day

    :param day: a workout day object
    :param nr_of_weeks: the numbrer of weeks to render, default is 7
    :param images: boolean indicating whether to also draw exercise images
           in the PDF (actually only the main image)
    :param comments: boolean indicathing whether the exercise comments will
           be rendered as well
    :param only_table: boolean indicating whether to draw a table with space
           for weight logs or just a list of the exercises
    '''

    # If rendering only the table, reset the nr of weeks, since these columns
    # will not be rendered anyway.
    if only_table:
        nr_of_weeks = 0

    data = []

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

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

    set_count = 1
    day_markers.append(len(data))

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

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
    data.append([_('Nr.'), _('Exercise'), _('Reps')] +
                [_('Weight')] * nr_of_weeks)

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

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

            # Process the settings
            if exercise['has_weight']:
                setting_out = []
                for i in exercise['setting_text'].split(u'–'):
                    setting_out.append(
                        Paragraph(i, styleSheet["Small"], bulletText=''))
            else:
                setting_out = Paragraph(exercise['setting_text'],
                                        styleSheet["Small"])

            # Collect a list of the exercise comments
            item_list = [Paragraph('', styleSheet["Small"])]
            if comments:
                item_list = [
                    ListItem(Paragraph(i,
                                       style=styleSheet["ExerciseComments"]))
                    for i in exercise['comment_list']
                ]

            # Add the exercise's main image
            image = Paragraph('', styleSheet["Small"])
            if images:
                if exercise['obj'].main_image:

                    # Make the images somewhat larger when printing only the workout and not
                    # also the columns for weight logs
                    if only_table:
                        image_size = 2
                    else:
                        image_size = 1.5

                    image = Image(exercise['obj'].main_image.image)
                    image.drawHeight = image_size * cm * image.drawHeight / image.drawWidth
                    image.drawWidth = image_size * cm

            # Put the name and images and comments together
            exercise_content = [
                Paragraph(exercise['obj'].name, styleSheet["Small"]), image,
                ListFlowable(item_list,
                             bulletType='bullet',
                             leftIndent=5,
                             spaceBefore=7,
                             bulletOffsetY=-3,
                             bulletFontSize=3,
                             start='square')
            ]

            data.append([set_count, exercise_content, setting_out] +
                        [''] * nr_of_weeks)
        set_count += 1

    table_style = [
        ('FONT', (0, 0), (-1, -1), 'OpenSans'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 2),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 3),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

        # Header
        ('BACKGROUND', (0, 0), (-1, 0), header_colour),
        ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
        ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
        ('SPAN', (0, 0), (-1, 0)),

        # Cell with 'date'
        ('SPAN', (0, 1), (2, 1)),
        ('ALIGN', (0, 1), (2, 1), 'RIGHT')
    ]

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

        table_style.append(
            ('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(
                ('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        if only_table:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 8 * cm  # Exercise
            t._argW[2] = 3.5 * cm  # Repetitions
        else:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 4 * cm  # Exercise
            t._argW[2] = 3 * cm  # Repetitions

    return KeepTogether(t)
コード例 #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 = ''
    if approval.title:
        title = approval.title

    #Organization details

    #address = proposal.applicant.organisation.postal_address
    address = proposal.relevant_applicant_address
    #email = proposal.applicant.organisation.organisation_set.all().first().contacts.all().first().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(approval.relevant_applicant_name, styles['BoldLeft']))
    elements.append(Paragraph(address.line1, styles['BoldLeft']))
    elements.append(Paragraph(address.line2, styles['BoldLeft']))
    elements.append(Paragraph(address.line3, 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 DISTURBANCE ACTIVITY IN {}'
            .format(title, proposal.lodgement_number,
                    region_district), styles['InfoTitleLargeLeft']))
    #import ipdb; ipdb.set_trace()
    #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(
        '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),
                approval.relevant_applicant_name))
    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 = None
    # Apiary Site Transfer requirements
    if proposal.application_type.name == ApplicationType.SITE_TRANSFER:
        requirements = proposal.apiary_requirements(approval).exclude(
            is_deleted=True)
    else:
        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))
    if user.phone_number:
        contact_number = user.phone_number
    elif user.mobile_number:
        contact_number = user.mobile_number
    else:
        contact_number = settings.DEP_PHONE

    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,
                                             contact_number, 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, styles['Left']))
                elements.append(Paragraph(item[key], styles['Left']))
    else:
        elements.append(
            Paragraph('There are no management actions.', styles['Left']))

    doc.build(elements)

    return approval_buffer
コード例 #5
0
ファイル: gen.py プロジェクト: rrader/dnd-pdf-gen-service
def gen(data, output):
    style = getSampleStyleSheet()
    headlineStyle = style["Heading2"]
    simple_paragraph = style["Normal"]
    # simple_paragraph.spaceAfter = inch * .04
    simple_paragraph.borderPadding = inch * .02
    simple_paragraph.alignment = TA_JUSTIFY
    highlighted_paragraph = simple_paragraph.clone("Highlighted")
    highlighted_paragraph.backColor = colors.toColor("#CCFF99")
    highlighted_paragraph.spaceAfter = inch * .02

    highlighted_paragraph2 = simple_paragraph.clone("Highlighted2")
    highlighted_paragraph2.backColor = colors.toColor("#CC9999")
    highlighted_paragraph2.spaceBefore = inch * .02

    powerHeader = style["Normal"].clone("PowerHeader")
    powerHeader.alignment = TA_JUSTIFY
    powerHeader.borderPadding = inch * .02
    powerHeader.textColor = colors.white
    # powerHeader.fontName = "Helvetica-Bold"
    powerHeader.fontSize = 9
    atwillHeader = powerHeader.clone("atWillHeader")
    atwillHeader.backColor = colors.toColor("#649769")

    encounterHeader = powerHeader.clone("encounterHeader")
    encounterHeader.backColor = colors.toColor("#981332")

    dailyHeader = powerHeader.clone("dailyHeader")
    dailyHeader.backColor = colors.toColor("#4C4C4E")

    utilityHeader = powerHeader.clone("utilityHeader")
    utilityHeader.backColor = colors.toColor("#336699")
    all_blocks = []
    # for i in range(5):
    #     headline = Paragraph("Hello world %d" % i, headlineStyle)
    #     blocks.append(headline)
    #     text = Paragraph(
    #         "I’ve added a content-disposition header. Instead of attachment, as you normally put into content-disposition, I’ve specified that the file should be displayed normally (which on some browsers will still be as an attachment if they don’t have the capability to inline-view PDF files). But by giving it a filename, if they do save the PDF they should get that as the default filename for the file.",
    #         paraStyle)
    #     blocks.append(text)
    tp_info = {
        'at-will': {
            'style': atwillHeader
        },
        'encounter': {
            'style': encounterHeader
        },
        'daily': {
            'style': dailyHeader
        },
        'utility': {
            'style': utilityHeader
        }
    }
    for tp_item in ['at-will', 'encounter', 'daily', 'utility']:
        for item in filter(None, data[tp_item]):
            tp = tp_item
            if tp == 'utility':
                if not item[0]:
                    continue
                tp = item[1]
                item = item[0]
            blocks = []
            blocks.append(flowables.HRFlowable(color=colors.black, spaceBefore=0, spaceAfter=2, width="100%", thickness=2))
            info = get_power_info(item)
            info['c'] = data
            info['attack_val'] = data.get(info["attack"].lower()+"_attack") or ["[no]", "[no]"]
            text = Paragraph("<b>{name}</b><br />{title}".format(**info), tp_info[tp_item]['style'])
            blocks.append(text)
            text = Paragraph(
                        """<u>{tp}</u><br />
                        <b>{action} Action</b> --- <b>Range:</b> {range}<br />
                        <b>Target:</b> {target}<br />
                        """.format(tp=tp.capitalize(), **info), simple_paragraph)
            blocks.append(text)
            if info['is_weapon'] == "yes":
                if info["attack"] == "complicated":
                    text = Paragraph("""
                                     <b>Attack:</b> {}
                                     """.format(info["attack_comment"]).format(**info), highlighted_paragraph)
                    blocks.append(text)
                elif info["attack"] not in ["trigger", "always"]:
                    text = Paragraph("""
                                     <b>Attack:</b> {attack} vs. {vs} [{attack_val[0]}] =<br/>= {attack_val[1]}
                                     """.format(**info), highlighted_paragraph)
                    blocks.append(text)
                weapons = [w[0].strip() for w in data["Attacks"] if w[0] and get_weapon_info(w[0])["range"] in info["range"].split(';')]
                for weapon in weapons:
                    d = get_weapon_info(weapon)
                    d.update(info)
                    hit = info["hit"].format(**d)
                    text = Paragraph(
                                    """
                                    <b>Hit w/ {weapon}:</b> {hit}
                                    """.format(weapon=d["weapon_name"], hit=hit), highlighted_paragraph2)
                    blocks.append(text)
                if not weapons:
                    try:
                        hit = info["hit"].format(**info)
                        text = Paragraph(
                                        """
                                        <b>Hit:</b> {hit}
                                        """.format(hit=hit), highlighted_paragraph2)
                        blocks.append(text)
                    except:
                        continue
                if info["hit_comment"]:
                    text = Paragraph(info["hit_comment"].format(**info), highlighted_paragraph2)
                    blocks.append(text)
            if info["comment"]:
                text = Paragraph(info["comment"].format(**info), simple_paragraph)
                blocks.append(text)
            blocks.append(flowables.HRFlowable(color=colors.black, spaceBefore=0, spaceAfter=2, width="100%", thickness=2))
            blocks.append(flowables.HRFlowable(color=colors.white, spaceBefore=0, spaceAfter=0, width="100%", thickness=3))
            block = KeepTogether(blocks)
            block.style = highlighted_paragraph2
            all_blocks.append(block)

    doc = BaseDocTemplate(output, pagesize=portrait(A4),
                          leftMargin=1.5*cm, rightMargin=1.5*cm,
                          topMargin=1.5*cm, bottomMargin=1.5*cm)
    frame_count = 2
    frame_width = doc.width / frame_count
    frame_height = doc.height - .05 * inch
    frames = []

    for frame in range(frame_count):
        left_margin = doc.leftMargin + frame * frame_width
        column = Frame(left_margin, doc.bottomMargin, frame_width, frame_height)
        frames.append(column)

    template = PageTemplate(frames=frames)
    doc.addPageTemplates(template)
    doc.build(all_blocks)
コード例 #6
0
ファイル: rl_doc_utils.py プロジェクト: biniyi/reportlab
def endKeep(s):
    S = getStory()
    k = KeepTogether(S[s:])
    S[s:] = [k]
コード例 #7
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

    #import ipdb; ipdb.set_trace()
    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(
        Paragraph('CONSERVATION AND LAND MANAGEMENT REGULATIONS 2002 (PART 7)',
                  styles['BoldCenter']))
    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 Director General of the Department of Biodiversity, Conservation and Attractions hereby grants a commercial operations 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 date of execution of this licence and expiring on {}'
            .format(approval.expiry_date.strftime(DATE_FORMAT)),
            styles['BoldLeft']))
    elements.append(
        Paragraph(
            'to enter upon and use the land within parks/ reserves in order to conduct activites as contained in the schedule attached to this Commercial Operations Licence.',
            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 Conservation and Land Management Act 1984 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 - Terrestrical and the Commercial Operator Handbook - Marine as varied from time to time by the Director General or his delegate.'
    )
    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', 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 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('License Number', styles['BoldLeft']),
        Paragraph(_format_name(approval.lodgement_number), 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)
    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:
        #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('[]')
        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)

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('SCHEDULE 2', 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
コード例 #8
0
ファイル: pdf.py プロジェクト: dolvany/dtrace-stap-book
 def __init__(self, para, img):
     self.img = img
     KeepTogether.__init__(self, [para, img])
コード例 #9
0
    def build_after_table(self):
        first_warning_text = "Die gelieferte Ware bleibt unser Eigentum bis zur Bezahlung sämtlicher auch künftig"\
                             " entstehender Forderungen aus unserer Geschäftsverbindung. Reklamationen können nur "\
                             "innerhalb von 2 Tagen nach Lieferung anerkannt werden."

        first_warning_paragraph = Paragraph(first_warning_text,
                                            size_ten_helvetica)

        first_warning_data = [
            [first_warning_paragraph,
             Paragraph("", size_ten_helvetica)],
        ]

        first_warning_table = Table(first_warning_data,
                                    colWidths=[430, 10],
                                    spaceBefore=20)

        first_warning_table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        second_warning_text = f"Reklamation von Waren können wir nur anerkennen, wenn diese unverzüglich nach der"\
                              f" Anlieferung erfolgen. Bitte prüfen Sie bei Lieferungen" \
                              f" unmittelbar die Ordnungsmäßigkeit"\
                              f" der Lieferung. Sollten Mängel oder Schäden an von uns gelieferten Waren festgestellt "\
                              f"werden, bitten wir Sie uns umgehend darüber zu informieren." \
                              f" Von Rücksendungen - ohne unsere"\
                              f" vorherige Zustimmung - bitten wir abzusehen."\
                              f"<br/><br/>"\
                              f"Retouren müssen nach unseren Richtlinien ordnungsgemäß zurück gesendet werden."

        second_warning_paragraph = Paragraph(second_warning_text,
                                             size_ten_helvetica)

        second_warning_data = [[
            second_warning_paragraph,
            Paragraph("", size_ten_helvetica)
        ]]

        second_warning_table = Table(second_warning_data,
                                     colWidths=[430, 10],
                                     spaceBefore=20)

        second_warning_table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        driver_form_title = Paragraph(
            "<br/><br/><b>Ware vollständig erhalten laut Lieferschein</b><br/><br/>",
            size_ten_helvetica)

        driver_data = [
            [driver_form_title],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Name Fahrer", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Kennzeichen", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Spedition", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Unterschrift Fahrer/Stempel", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            # [Paragraph(f"Name Fahrer:{underline}", size_ten_helvetica)],
            # [],
            # [Paragraph(f"Kennzeichen:{underline}", size_ten_helvetica)],
            # [],
            # [Paragraph(f"Spedition:{underline}", size_ten_helvetica)],
            # [],
            # [],
            # [Paragraph(f"Unterschrift Fahrer/Stempel:{underline}", size_ten_helvetica)],
            # []
        ]

        driver_table = Table(driver_data, colWidths=[320, 100])

        driver_table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        quality_form_title = Paragraph(
            "<br/><br/><b>Qualitätskontrolle</b><br/><br/>",
            size_ten_helvetica)

        quality_data = [
            [quality_form_title],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Name Kommissionierer", size_nine_helvetica),
                Paragraph("Datum/Unterschrift", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Name Kontrolleur", size_nine_helvetica),
                Paragraph("Datum/Unterschrift", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Name Verlader", size_nine_helvetica),
                Paragraph("Datum/Unterschrift", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
            [
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph(f"{underline}___", size_ten_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [
                Paragraph("Name Verantwortlicher", size_nine_helvetica),
                Paragraph("Datum/Unterschrift", size_nine_helvetica),
                Paragraph("", size_ten_helvetica)
            ],
            [],
        ]

        quality_form_table = Table(quality_data, colWidths=[195, 240, 0])

        quality_form_table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        driver_and_quality_data = [
            [driver_table],
            [quality_form_table],
        ]

        driver_and_quality_table = Table(driver_and_quality_data)

        self.story.extend([
            first_warning_table,
            KeepTogether(driver_and_quality_table), second_warning_table
        ])
コード例 #10
0
ファイル: helpers.py プロジェクト: michal-stuglik/wger
def render_workout_day(day, nr_of_weeks):
    '''
    Render a table with reportlab with the contents of the training day
    '''

    data = []

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

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

    set_count = 1
    day_markers.append(len(data))

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

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
    data.append([_('Nr.'), _('Exercise'), _('Reps')] +
                [_('Weight')] * nr_of_weeks)

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

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

            data.append([
                set_count,
                Paragraph(exercise['obj'].name, styleSheet["Small"]),
                exercise['setting_text']
            ] + [''] * nr_of_weeks)
        set_count += 1

    table_style = [
        ('FONT', (0, 0), (-1, -1), 'OpenSans'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 2),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 3),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

        # Header
        ('BACKGROUND', (0, 0), (-1, 0), header_colour),
        ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
        ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
        ('SPAN', (0, 0), (-1, 0)),

        # Cell with 'date'
        ('SPAN', (0, 1), (2, 1)),
        ('ALIGN', (0, 1), (2, 1), 'RIGHT')
    ]

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

        table_style.append(
            ('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(
                ('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        t._argW[0] = 0.6 * cm  # Numbering
        t._argW[1] = 4 * cm  # Exercise
        t._argW[2] = 2 * cm  # Repetitions

    return KeepTogether(t)
コード例 #11
0
                         FlexParagraph(volume,
                                       small_text,
                                       margin=(10, 0, 0),
                                       border=(1, 0, 0),
                                       border_color="#000000",
                                       background_color="#ff0000",
                                       padding=5),
                         border=1,
                         border_color="#000000",
                         width="50%",
                         flex_direction=FlexDirection.Column,
                         align_items=JustifyContent.FlexCenter)


if __name__ == "__main__":
    doc = DemoDocTemplate("options_demo", timestamp=True)
    doc.build(flowables=[
        FlexParagraph("Wrap", h1, padding=(spacing * 2, 0, 0)),
        wrap,
        FlexParagraph("JustifyContent", h1, padding=(spacing * 2, 0, 0)),
        justify_content,
        FlexParagraph("AlignItems", h1, padding=(spacing * 2, 0, 0)),
        align_items,
        KeepTogether(flowables=[
            FlexParagraph("AlignContent", h1, padding=(spacing * 2, 0, 0)),
            align_content,
        ]),
        FlexParagraph("TankPlate", h1, padding=(spacing * 2, 0, spacing)),
        TankPlate("Cistern A2", "Acetone", "Volume 5000 [L]"),
    ])
コード例 #12
0
ファイル: document.py プロジェクト: Eggiverse/pdfdocument
 def end_keeptogether(self):
     keeptogether = KeepTogether(self.story[self.keeptogether_index:])
     self.story = self.story[:self.keeptogether_index]
     self.story.append(keeptogether)
コード例 #13
0
ファイル: ICRJsonToHtml.py プロジェクト: sethrylan/VistA
def _writeComponentEntryPointToPDF(section, pdf, doc):
    for component in section:
        componentSection = []
        name = component["COMPONENT/ENTRY POINT"]
        componentSection.append(
            Paragraph("%s : %s" % ("COMPONENT/ENTRY POINT", name),
                      STYLES['Heading3']))
        if 'COMPONENT DESCRIPTION' in component:
            # TODO: Each line should be its own Paragraph
            description = component["COMPONENT DESCRIPTION"]
            if type(description) is list:
                description = " ".join(description)
            componentSection.append(
                _convertIndividualFieldValuePDF('COMPONENT DESCRIPTION',
                                                description, True))
            componentSection.append(Spacer(1, 20))
        if 'VARIABLES' in component:
            variables = component["VARIABLES"]
            table = []
            table.append(
                generatePDFTableHeader(
                    ["VARIABLES", "TYPE", "VARIABLES DESCRIPTION"]))
            for variable in variables:
                if type(variable) is dict:
                    row = []
                    _variables = variable['VARIABLES']
                    if type(_variables) is list:
                        _variables = _variables[0]
                        if "-" in _variables:
                            # TODO: This is a workaround for an error in original
                            # file, see ICR-639. This does not create an error
                            # when creating the html file, but the formating is
                            # incorrect.
                            variable['VARIABLES'] = _variables.split("-")[0]
                            variable[
                                'VARIABLES DESCRIPTION'] = _variables.split(
                                    "-")[1]
                        else:
                            # TODO: ICR-5317 VARIABLES are not
                            # parsed correctly. Skip them for now.
                            variable['VARIABLES'] = ""
                    row.append(
                        _convertIndividualFieldValuePDF(
                            'VARIABLES', variable['VARIABLES'], False))
                    if 'TYPE' in variable:
                        if type(variable['TYPE']) is list:
                            # TODO: ICR-6551 VARIABLES are not
                            # parsed correctly. Skip them for now.
                            variable['TYPE'] = ""
                        row.append(
                            _convertIndividualFieldValuePDF(
                                'TYPE', variable['TYPE'], False, False))
                    else:
                        row.append(Paragraph("", STYLES['Normal']))
                    if 'VARIABLES DESCRIPTION' in variable:
                        description = variable['VARIABLES DESCRIPTION']
                        if type(description) is list:
                            description = " ".join(description)
                            if len(description) > 1000:
                                # TODO: Skipping long descriptions for now
                                # See ICR-2916, ICR-3486, etc.
                                description = ""
                        row.append(
                            _convertIndividualFieldValuePDF(
                                'VARIABLES DESCRIPTION', description, False,
                                False))
                    else:
                        row.append(Paragraph("", STYLES['Normal']))
                    table.append(row)
                else:
                    # TODO: Parsing error! See ICR-28
                    pass
            columns = 10
            columnWidth = doc.width / columns
            t = Table(
                table,
                colWidths=[columnWidth * 2, columnWidth, columnWidth * 7])
            t.setStyle(
                TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))
            componentSection.append(t)
        pdf.append(KeepTogether(componentSection))
コード例 #14
0
                          equity_name,
                          bought_date.strftime('%d/%m/%Y'),
                          sold_date.strftime('%d/%m/%Y'),
                          '£' + str(profit_loss), return_pc
                      ]]
        table = Table(table_data)
        # Set table style. (From cell) (To cell) (col, row)
        table.setStyle(
            TableStyle([('FONTNAME', (0, 0), (-1, -1), 'Palatino Linotype'),
                        ('FONTSIZE', (0, 0), (-1, -1), 9),
                        ('INNERGRID', (0, 0), (-1, -1), 1, colors.grey),
                        ('BACKGROUND', (3, -1), (4, -1), profit_loss_color)]))

        # Use KeepTogether flowable to ensure line, spacer, chartRL etc. flowables all stay together for each equity.
        story.append(
            KeepTogether([
                line,
                Spacer(5, 6), equityText,
                Spacer(5, 4), chartRL,
                Spacer(5, 2), table,
                Spacer(5, 30)
            ]))
    else:
        continue

# Close all plots
plt.close('all')

# Build pdf. Can also annotate page numbers, logos onto pages. Building pdf creates Canvas object, can be accessed by .canv
# Build pdf can also take onPage static drawing functions. Haven't tried this yet
pdf.build(story)
コード例 #15
0
def generate_pdf_cotizacion(request,id_cotizacion):
	
	# Declaracion de variables
	iva = 12
	path = './sistema_sfc/static/images/'
	total = 0
	elements = []
	total_productos = []
	objeto = {"cantidad":0, "descripcion":0, "talla":0, "precio_unitario":0, "precio_total":0}

	# Declaracion variables del apartado 'Observaciones' de la cotizacion
	tiempo_entrega = 15
	periodo_validez = 2
	condicion_pago_final = 50
	condicion_pago_inicial = 50
	
	# convertir a formato string para ser dibujado en la cotizacion
	tiempo_entrega_str = str(tiempo_entrega)
	periodo_validez_str = str(periodo_validez)
	condicion_pago_final_str = str(condicion_pago_final)
	condicion_pago_inicial_str = str(condicion_pago_inicial)	

	# Informacion de la cotizacion con id = id_cotizacion
	cotizacion = Cotizacion.objects.get(id = id_cotizacion)
	
	# Productos pertenecientes a la cotizacion con id = id_cotizacion
	productos_cotizacion = Producto_has_cotizacion.objects.filter(cotizacion_id_cotizacion_id = cotizacion.id).extra(select={'cotizacion_id_cotizacion_id':cotizacion.id})
	
	# Todos los productos
	productos = Producto.objects.order_by('id')
	
	# Cliente perteneciente a la cotizacion con id = id_cotizacion
	cliente = Cliente.objects.get(id=cotizacion.cliente_identificacion_id)

	# Observaciones pertenecientes a la cotizacion con id = id_cotizacion
	observaciones_cotizacion = Observacion.objects.filter(cotizacion_id = cotizacion.id).extra(select={'cotizacion_id':cotizacion.id})
	
	
	# Ciclo para obtener todos los productos con su cantidad, talla y precio para ser dibujado en
	# la tabla, el resultado se almacena en el array 'total_productos' de objetos con el formato:
	# {"cantidad":0, "descripcion":0, "talla":0, "precio_unitario":0, "precio_total":0}
	# y el subtotal (suma de todo los precios) en la variable total.

	for item in productos_cotizacion:
		for producto in productos:
			if producto.id == item.producto_id_producto_id:
				objeto['descripcion'] = producto.descripcion
				break
		objeto['cantidad'] = item.cantidad
		objeto['talla'] = item.talla
		objeto['precio_unitario'] = item.precio
		objeto['precio_total'] = (item.precio * item.cantidad)*(1+(item.ganancia / 100))
		total_productos.append(objeto)
		total += (item.precio * item.cantidad)*(1+(item.ganancia / 100))
		objeto = {"cantidad":0, "descripcion":0, "talla":0, "precio_unitario":0, "precio_total":0}

	# Calculo de subtotal, iva, total
	sub_total = total
	iva_total = (total * iva) / 100
	total = iva_total + sub_total

	response = HttpResponse(content_type='application/pdf')
	response['Content-Disposition'] = 'attachment; filename="COTIZACION '+id_cotizacion+' '+cliente.nombre+'.pdf"'


	# Creacion del pdf 
	# Creacion de la hoja de pdf
	styles = getSampleStyleSheet()
	doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
	
	# Logo de la Empresa
	name_logo = path + "logo.png"
	imagen = Image(name_logo, width=240, height=93)
	imagen.hAlign = 'LEFT'
	elements.append(imagen)
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, -90))

	# icono de telefono
	name_icon_telefono = path + "icon-phone.jpg"
	com_telefono = 'canvas.drawImage("'+name_icon_telefono+'",320,-20,12,12)'
	elements.append(flowables.Macro(com_telefono))
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 8))
	
	# Agregar estilo al texto del telefono
	ps = ParagraphStyle("indented")
	ps.leftIndent = 340
	texto_telefono = Paragraph('0414-863.67.29 / 0424-919.89.92', ps)
	elements.append(texto_telefono)

	# icono de twitter
	name_icon_twitter = path + "icon-twitter.jpg"
	com_twitter = 'canvas.drawImage("'+name_icon_twitter+'",320,-20,12,12)'
	elements.append(flowables.Macro(com_twitter))
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 8))
	
	# Agregar estilo al texto
	ps = ParagraphStyle("indented")
	ps.leftIndent = 340
	texto_twitter = Paragraph('diseña2guayana', ps)
	elements.append(texto_twitter)

	# icono de facebook
	name_icon_facebook = path + "icon-facebook.jpg"
	com_facebook = 'canvas.drawImage("'+name_icon_facebook+'",320,-20,12,12)'
	elements.append(flowables.Macro(com_facebook))
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 8))
	
	# Agregar estilo al texto
	ps = ParagraphStyle("indented")
	ps.leftIndent = 340
	texto_facebook = Paragraph('diseña2guayana', ps)
	elements.append(texto_facebook)

	# icono de correo gmail
	name_icon_gmail = path + "icon-gmail.jpg"
	com_gmail = 'canvas.drawImage("'+name_icon_gmail+'",320,-20,12,12)'
	elements.append(flowables.Macro(com_gmail))
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 8))
	
	# Agregar estilo al texto
	ps = ParagraphStyle("indented")
	ps.leftIndent = 340
	texto_gmail = Paragraph('diseñ[email protected]', ps)
	elements.append(texto_gmail)

	# icono de la web
	name_icon_web = path + "icon-web.jpg"
	com_web = 'canvas.drawImage("'+name_icon_web+'",320,-20,12,12)'
	elements.append(flowables.Macro(com_web))
	
	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 8))
	
	# Agregar estilo al texto
	ps = ParagraphStyle("indented")
	ps.leftIndent = 340
	texto_web = Paragraph('www.diseña2guayana.com', ps)
	elements.append(texto_web)

	# Espacio y estilo del texto nombre de la empresa
	elements.append(Spacer(0, 15))
	ps = ParagraphStyle("indented")
	ps.leftIndent = 70
	texto  = Paragraph('DISEÑA2 GUAYANA, C.A.', ps)
	elements.append(texto )

	# Espacio y estilo del texto rif de la empresa
	ps = ParagraphStyle("indented")
	ps.leftIndent = 85
	texto  = Paragraph('RIF: J-31706245-0', ps)
	elements.append(texto )

	# Espacio y estilo de la oferta y garantia
	elements.append(Spacer(0, -25))
	ps = ParagraphStyle(
        'normal',leftIndent=320, textColor= "blue", fontName='Helvetica-Bold',)
	
	texto  = Paragraph('Envíos y entregas gratis a nivel regional!', ps)
	elements.append(texto )

	ps = ParagraphStyle(
        'normal',leftIndent=380, textColor= "blue", fontName='Helvetica-Bold',)
	texto  = Paragraph('Garantía 100% ', ps)
	elements.append(texto )

	# annadir espacio derecho en la hoja pdf
	elements.append(Spacer(0, 10))
	
	# Parrafos para la informacion del cliente
	ps = ParagraphStyle(
        'normal',textColor= "black", fontName='Helvetica-Bold')
	P0 = Paragraph('Cliente:   '+cliente.nombre, ps)
	P1 = Paragraph('Fecha:   '+str(cotizacion.fecha).split(' ')[0],ps)
	P2 = Paragraph('Rif:   '+str(cliente.rif), ps)
	P3 = Paragraph('Cotización:   '+str(cotizacion.id), ps)
	P4 = Paragraph('Teléfono:   '+str(cliente.telefono), ps)
	P5 = Paragraph('Correo:   '+str(cliente.correo), ps)

	# Tabla con la infrmacion del cliente
	data= [[P0, P1], [P2,P3], [P4,P5]]
	t=Table(data,colWidths=[310, 220], style=[
                    ('BOX',(0,0),(-1,-1),0,colors.black),
                    ('GRID',(0,0),(-1,-1),0.5,colors.black)])
	
	# Alineacion y agregar tabla a la hoja pdf
	t.hAlign = 'LEFT'
	elements.append(t)

	# tabla con le texto informativo
	data= [['Tenemos el agrado de cotizarle los siguientes productos y o servicios']]
	t=Table(data,colWidths=[530], rowHeights=[30], style=[
                    ('BOX',(0,0),(-0,-0),0,colors.black),
                    ('GRID',(0,0),(-0,-0),0.5,colors.black),

                    ('VALIGN',(0,0),(-1,-1),'MIDDLE')])
	
	# Alineacion y agregar tabla a la hoja pdf
	t.hAlign = 'LEFT'
	elements.append(t)

	# Estilos y arreglo para el ****Header***** de la Tabla
	ps = ParagraphStyle(
        'normal',textColor= "black", fontName='Helvetica-Bold', alignment=TA_CENTER,)
	P0 = Paragraph('Item', ps)
	P1 = Paragraph('Descripción', ps)
	P2 = Paragraph('Cantidad', ps)
	P3 = Paragraph('Precio', ps)
	P4 = Paragraph('Monto', ps)

	data= [[P0, P1, P2, P3, P4]]
	
	# estlo para el contenido de la tabla
	centered = ParagraphStyle(name="centered", alignment=TA_CENTER)

    # tabla para agregar los productos y contador para dibujar el numero de productos   
	table = []
	item = 1
	
	# ciclo para dibujar los productos con su estilo en pdf
	for producto in total_productos:
		item1 = Paragraph(str(item), centered)
		item2 = Paragraph(str(producto['descripcion'])+'; Tallas: '+str(producto['talla']), centered)
		item3 = Paragraph(str(producto['cantidad']), centered)
		item4 = Paragraph(str(producto['precio_unitario']), centered)
		item5 = Paragraph(str(producto['precio_total']), centered)
		
		table.append([item1,item2,item3,item4,item5])
		item +=1
	
	#  Estilo y texto de 'SUB-TOTAL' | 'IVA 12%' | 'TOTAL'
	ps = ParagraphStyle('normal',textColor= "black",fontName='Helvetica-Bold', alignment=TA_RIGHT,)
	sub_total_text = Paragraph('SUB-TOTAL',ps)
	iva_text = Paragraph('IVA 12%',ps)
	total_text = Paragraph('TOTAL',ps)

	# Fila para el subtotal, iva y total
	table_row1 = ['',sub_total_text,'','',sub_total]
	table_row2 = ['',iva_text,'','',iva_total]
	table_row3 = ['',total_text,'','',total]
	
	# Agregar a Tabla momentanea de productos
	table.append(table_row1)
	table.append(table_row2)
	table.append(table_row3)
	
	# agregar a tabla final
	for item in table:
		data.append(item)
	
	# Crear la tabla formato para dibujar en PDF

	t2=Table(data, colWidths=[60, 200, 90, 90, 90], style=[
                    ('BOX',(0,0),(-1,-1),0,colors.black),
                    ('GRID',(0,0),(-1,-1),0.5,colors.black),             
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE')])
	t2.hAlign = 'LEFT'
	elements.append(t2)

	elements.append(Spacer(0, 20))
	
	# Estilos para el apartado de Observaciones del pdf
	ps = ParagraphStyle(
        'normal',textColor= "black")
	ps0 = ParagraphStyle(
        'normal',textColor= "black",fontName='Helvetica-Bold', alignment=TA_CENTER,)
	ps1 = ParagraphStyle(
        'normal',fontName='Helvetica-Bold',textColor= "black")
	ps2 = ParagraphStyle(
        'normal',fontName='Helvetica-Bold',textColor= "red")

	P0 = Paragraph('OBSERVACIONES', ps0)
	data = [[P0]]
	for item in observaciones_cotizacion:
		P1 = Paragraph('* '+ item.descripcion, ps)
		data.append([P1])

	'''P0 = Paragraph("* El trabajo se iniciará una vez recibido el pago del  50% de anticipo y la orden de compra correspondiente", ps)
	P1 = Paragraph('* Condición de Pago: '+condicion_pago_inicial_str+' con la  aprobación del presupuesto y '+condicion_pago_final_str+' a la entrega del pedido', ps1)
	P2 = Paragraph('* Los precios unitario no incluyen Iva', ps)
	P3 = Paragraph('* Los precios anexos son en base a esa cantidad solicitada, para otro monto debe consultar', ps)
	P4 = Paragraph('* Los precios y disponibilidad están sujetos a cambios', ps2)
	P5 = Paragraph('* Tiempo de entrega: '+tiempo_entrega_str+' días hábiles', ps)
	P6 = Paragraph('* Validez de la Cotización: '+periodo_validez_str+' días', ps)'''

	# Tabla con las observaciones del PDf
	# data= [[P7],[P0],[P1], [P2] , [P3], [P4], [P5], [P6]]

	t1=Table(data,colWidths=[520], style=[
                    ('BOX',(0,0),(-1,-1),0,colors.black),
                    ('GRID',(0,0),(-1,-1),0.5,colors.black),             
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE')])
	
	t1.hAlign = 'LEFT'
	t1.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.green)]))
	t2 = KeepTogether(t1)
	elements.append(t2)
	#elements.append(t1)

	
	# Estilos y parrafos con las firmas del cliente y de la empresa
	ps = ParagraphStyle(
        'normal',textColor= "black",leftIndent=80)
	firma_cliente = Paragraph(cliente.nombre, ps)

	ps = ParagraphStyle(
        'normal',textColor= "black", leftIndent=340)
	firma_disena2Guayana = Paragraph('Diseña2 Guayana, C.A.', ps)

	elements.append(Spacer(0, 50))
	elements.append(firma_cliente)
	elements.append(Spacer(0, -11))
	elements.append(firma_disena2Guayana)

	elements.append(Spacer(0, 50))
	
	# Construir el PDF
	doc.build(elements)
	#doc.build(elements, canvasmaker=NumberedCanvas)
	
	return response
コード例 #16
0
ファイル: invoice.py プロジェクト: zhangzhongnan928/pretix
    def _get_story(self, doc):
        has_taxes = any(il.tax_value for il in self.invoice.lines.all())

        story = [
            NextPageTemplate('FirstPage'),
            Paragraph(
                (
                    pgettext('invoice', 'Tax Invoice') if str(self.invoice.invoice_from_country) == 'AU'
                    else pgettext('invoice', 'Invoice')
                ) if not self.invoice.is_cancellation else pgettext('invoice', 'Cancellation'),
                self.stylesheet['Heading1']
            ),
            Spacer(1, 5 * mm),
            NextPageTemplate('OtherPages'),
        ]
        story += self._get_intro()

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

        tstyledata = [
            ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('FONTNAME', (0, 0), (-1, 0), self.font_bold),
            ('FONTNAME', (0, -1), (-1, -1), self.font_bold),
            ('LEFTPADDING', (0, 0), (0, -1), 0),
            ('RIGHTPADDING', (-1, 0), (-1, -1), 0),
        ]
        if has_taxes:
            tdata = [(
                pgettext('invoice', 'Description'),
                pgettext('invoice', 'Qty'),
                pgettext('invoice', 'Tax rate'),
                pgettext('invoice', 'Net'),
                pgettext('invoice', 'Gross'),
            )]
        else:
            tdata = [(
                pgettext('invoice', 'Description'),
                pgettext('invoice', 'Qty'),
                pgettext('invoice', 'Amount'),
            )]

        total = Decimal('0.00')
        for line in self.invoice.lines.all():
            if has_taxes:
                tdata.append((
                    Paragraph(line.description, self.stylesheet['Normal']),
                    "1",
                    localize(line.tax_rate) + " %",
                    money_filter(line.net_value, self.invoice.event.currency),
                    money_filter(line.gross_value, self.invoice.event.currency),
                ))
            else:
                tdata.append((
                    Paragraph(line.description, self.stylesheet['Normal']),
                    "1",
                    money_filter(line.gross_value, self.invoice.event.currency),
                ))
            taxvalue_map[line.tax_rate, line.tax_name] += line.tax_value
            grossvalue_map[line.tax_rate, line.tax_name] += line.gross_value
            total += line.gross_value

        if has_taxes:
            tdata.append([
                pgettext('invoice', 'Invoice total'), '', '', '', money_filter(total, self.invoice.event.currency)
            ])
            colwidths = [a * doc.width for a in (.50, .05, .15, .15, .15)]
        else:
            tdata.append([
                pgettext('invoice', 'Invoice total'), '', money_filter(total, self.invoice.event.currency)
            ])
            colwidths = [a * doc.width for a in (.65, .05, .30)]

        if self.invoice.event.settings.invoice_show_payments and not self.invoice.is_cancellation and \
                self.invoice.order.status == Order.STATUS_PENDING:
            pending_sum = self.invoice.order.pending_sum
            if pending_sum != total:
                tdata.append([pgettext('invoice', 'Received payments')] + (['', '', ''] if has_taxes else ['']) + [
                    money_filter(pending_sum - total, self.invoice.event.currency)
                ])
                tdata.append([pgettext('invoice', 'Outstanding payments')] + (['', '', ''] if has_taxes else ['']) + [
                    money_filter(pending_sum, self.invoice.event.currency)
                ])
                tstyledata += [
                    ('FONTNAME', (0, len(tdata) - 3), (-1, len(tdata) - 3), self.font_bold),
                ]

        table = Table(tdata, colWidths=colwidths, repeatRows=1)
        table.setStyle(TableStyle(tstyledata))
        story.append(table)

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

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

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

        tstyledata = [
            ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
            ('LEFTPADDING', (0, 0), (0, -1), 0),
            ('RIGHTPADDING', (-1, 0), (-1, -1), 0),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('FONTNAME', (0, 0), (-1, -1), self.font_regular),
        ]
        thead = [
            pgettext('invoice', 'Tax rate'),
            pgettext('invoice', 'Net value'),
            pgettext('invoice', 'Gross value'),
            pgettext('invoice', 'Tax'),
            ''
        ]
        tdata = [thead]

        for idx, gross in grossvalue_map.items():
            rate, name = idx
            if rate == 0:
                continue
            tax = taxvalue_map[idx]
            tdata.append([
                localize(rate) + " % " + name,
                money_filter(gross - tax, self.invoice.event.currency),
                money_filter(gross, self.invoice.event.currency),
                money_filter(tax, self.invoice.event.currency),
                ''
            ])

        def fmt(val):
            try:
                return vat_moss.exchange_rates.format(val, self.invoice.foreign_currency_display)
            except ValueError:
                return localize(val) + ' ' + self.invoice.foreign_currency_display

        if len(tdata) > 1 and has_taxes:
            colwidths = [a * doc.width for a in (.25, .15, .15, .15, .3)]
            table = Table(tdata, colWidths=colwidths, repeatRows=2, hAlign=TA_LEFT)
            table.setStyle(TableStyle(tstyledata))
            story.append(Spacer(5 * mm, 5 * mm))
            story.append(KeepTogether([
                Paragraph(pgettext('invoice', 'Included taxes'), self.stylesheet['FineprintHeading']),
                table
            ]))

            if self.invoice.foreign_currency_display and self.invoice.foreign_currency_rate:
                tdata = [thead]

                for idx, gross in grossvalue_map.items():
                    rate, name = idx
                    if rate == 0:
                        continue
                    tax = taxvalue_map[idx]
                    gross = round_decimal(gross * self.invoice.foreign_currency_rate)
                    tax = round_decimal(tax * self.invoice.foreign_currency_rate)
                    net = gross - tax

                    tdata.append([
                        localize(rate) + " % " + name,
                        fmt(net), fmt(gross), fmt(tax), ''
                    ])

                table = Table(tdata, colWidths=colwidths, repeatRows=2, hAlign=TA_LEFT)
                table.setStyle(TableStyle(tstyledata))

                story.append(KeepTogether([
                    Spacer(1, height=2 * mm),
                    Paragraph(
                        pgettext(
                            'invoice', 'Using the conversion rate of 1:{rate} as published by the European Central Bank on '
                                       '{date}, this corresponds to:'
                        ).format(rate=localize(self.invoice.foreign_currency_rate),
                                 date=date_format(self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT")),
                        self.stylesheet['Fineprint']
                    ),
                    Spacer(1, height=3 * mm),
                    table
                ]))
        elif self.invoice.foreign_currency_display and self.invoice.foreign_currency_rate:
            foreign_total = round_decimal(total * self.invoice.foreign_currency_rate)
            story.append(Spacer(1, 5 * mm))
            story.append(Paragraph(
                pgettext(
                    'invoice', 'Using the conversion rate of 1:{rate} as published by the European Central Bank on '
                               '{date}, the invoice total corresponds to {total}.'
                ).format(rate=localize(self.invoice.foreign_currency_rate),
                         date=date_format(self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT"),
                         total=fmt(foreign_total)),
                self.stylesheet['Fineprint']
            ))

        return story
コード例 #17
0
def _create_licence(licence_buffer, licence, application, site_url, original_issue_date):
    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_licence_header)

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

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

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

    elements = []

    elements.append(Paragraph(licence.licence_type.act, styles['InfoTitleLargeCenter']))
    elements.append(Paragraph(licence.licence_type.code.upper(), styles['InfoTitleLargeCenter']))

    # cannot use licence get_title_with_variants because licence isn't saved yet so can't get variants
    if application.variants.exists():
        title = '{} ({})'.format(application.licence_type.name.encode('UTF-8'), ' / '.join(application.variants.all().
                                                                           values_list('name', flat=True)))
    else:
        title = licence.licence_type.name.encode('UTF-8')

    elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    elements.append(Paragraph(licence.licence_type.statement, styles['InfoTitleLargeLeft']))
    elements.append(Paragraph(licence.licence_type.authority, styles['InfoTitleLargeRight']))

    # licence conditions
    if application.conditions.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Conditions', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

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

    # purpose
    if licence.purpose:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Purpose', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements += _layout_paragraphs(licence.purpose)

    # locations
    if licence.locations:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Locations', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements += _layout_paragraphs(licence.locations)

    elements += _layout_extracted_fields(licence.extracted_fields)

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

    # delegation holds the dates, licencee 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(licence.issue_date.strftime(DATE_FORMAT), styles['Left']),
                   Paragraph(licence.start_date.strftime(DATE_FORMAT), styles['Left']),
                   Paragraph(licence.end_date.strftime(DATE_FORMAT), styles['Left'])]

    if original_issue_date is not None:
        date_headings.insert(0, Paragraph('Original Date of Issue', styles['BoldLeft']))
        date_values.insert(0, Paragraph(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))

    # licensee details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    address = application.applicant_profile.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(application.applicant, include_first_name=True),
                                         styles['Left'])] + address_paragraphs]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=licence_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Issued by a Wildlife Licensing Officer of the Department of Parks and Wildlife '
                                'under delegation from the Minister for Environment pursuant to section 133(1) '
                                'of the Conservation and Land Management Act 1984.', styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return licence_buffer
コード例 #18
0
ファイル: pdf.py プロジェクト: dolvany/dtrace-stap-book
 def wrap(self, aW, aH):
     return KeepTogether.wrap(self, aW, aH)
コード例 #19
0
def _create_approval(approval_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(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')])

    elements = []

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

    elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    elements.append(Paragraph(approval.activity, styles['InfoTitleLargeLeft']))
    elements.append(Paragraph(approval.region, styles['InfoTitleLargeLeft']))
    elements.append(
        Paragraph(approval.tenure if approval.tenure else '',
                  styles['InfoTitleLargeRight']))

    # proposal requirements
    if proposal.requirements.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Requirements', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

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

    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(
            'Issued by a Disturbance Licensing Officer of the {} '
            'under delegation from the Minister for Environment pursuant to section 133(1) '
            'of the Conservation and Land Management Act 1984.'.format(
                settings.DEP_NAME), styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return approval_buffer