예제 #1
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
예제 #2
0
파일: invoices.py 프로젝트: tydonk/pretix
def _invoice_generate_german(invoice, f):
    _invoice_register_fonts()
    styles = _invoice_get_stylesheet()
    pagesize = pagesizes.A4

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

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

        canvas.restoreState()

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

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

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

        textobject = canvas.beginText(25 * mm, (297 - 15) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(pgettext('invoice', 'Invoice from').upper())
        canvas.drawText(textobject)

        p = Paragraph(invoice.invoice_from.strip().replace('\n', '<br />\n'),
                      style=styles['Normal'])
        p.wrapOn(canvas, 70 * mm, 50 * mm)
        p_size = p.wrap(70 * mm, 50 * mm)
        p.drawOn(canvas, 25 * mm, (297 - 17) * mm - p_size[1])

        textobject = canvas.beginText(25 * mm, (297 - 50) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(pgettext('invoice', 'Invoice to').upper())
        canvas.drawText(textobject)

        p = Paragraph(invoice.invoice_to.strip().replace('\n', '<br />\n'),
                      style=styles['Normal'])
        p.wrapOn(canvas, 85 * mm, 50 * mm)
        p_size = p.wrap(85 * mm, 50 * mm)
        p.drawOn(canvas, 25 * mm, (297 - 52) * mm - p_size[1])

        textobject = canvas.beginText(125 * mm, (297 - 38) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(_('Order code').upper())
        textobject.moveCursor(0, 5)
        textobject.setFont('OpenSans', 10)
        textobject.textLine(invoice.order.full_code)
        canvas.drawText(textobject)

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

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

        canvas.drawText(textobject)

        if invoice.event.settings.invoice_logo_image:
            logo_file = invoice.event.settings.get('invoice_logo_image',
                                                   binary_file=True)
            canvas.drawImage(ImageReader(logo_file),
                             95 * mm, (297 - 38) * mm,
                             width=25 * mm,
                             height=25 * mm,
                             preserveAspectRatio=True,
                             anchor='n',
                             mask='auto')

        if invoice.event.settings.show_date_to:
            p_str = (str(invoice.event.name) + '\n' +
                     _('{from_date}\nuntil {to_date}').format(
                         from_date=invoice.event.get_date_from_display(),
                         to_date=invoice.event.get_date_to_display()))
        else:
            p_str = (str(invoice.event.name) + '\n' +
                     invoice.event.get_date_from_display())

        p = Paragraph(p_str.strip().replace('\n', '<br />\n'),
                      style=styles['Normal'])
        p.wrapOn(canvas, 65 * mm, 50 * mm)
        p_size = p.wrap(65 * mm, 50 * mm)
        p.drawOn(canvas, 125 * mm, (297 - 17) * mm - p_size[1])

        textobject = canvas.beginText(125 * mm, (297 - 15) * mm)
        textobject.setFont('OpenSansBd', 8)
        textobject.textLine(_('Event').upper())
        canvas.drawText(textobject)

        canvas.restoreState()

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

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

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

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

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

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

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

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

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

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

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

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

    doc.build(story)
    return doc
예제 #3
0
    def _set_style(self):
        self.frame = Frame(1.1 * cm,
                           6.2 * cm,
                           self.PAGE_WIDTH - 2.4 * cm,
                           self.PAGE_HEIGHT - 12 * cm,
                           leftPadding=0,
                           rightPadding=0)
        self.paragraph_estile_1 = ParagraphStyle('',
                                                 fontName='DejaVu',
                                                 fontSize=12,
                                                 alignment=0)

        self.table_style = TableStyle([
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            ('TOPPADDING', (0, 0), (-1, -1), 0),
            ('LEFTPADDING', (1, 0), (-3, -1), 0),
            ('FONT', (0, 0), (-1, -1), self.normal, 12),
            ('FONT', (2, 0), (3, -1), self.normal, 9),
            ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
            ('ALIGN', (1, 0), (1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])
        self.first_page = PageTemplate(id='1st_page',
                                       frames=self.frame,
                                       onPage=self._render_page)

        # check if target directory exists
        dirname = os.path.dirname(self.invoice.path)
        if not os.path.exists(dirname):
            os.mkdir(dirname)

        self.sheet_style = BaseDocTemplate(
            self.invoice.path,
            pagesize=A4,
            pageTemplates=[self.first_page],
            showBoundary=0,
            leftMargin=0,
            rightMargin=0,
            topMargin=0,
            bottomMargin=0,
            allowSplitting=1,
            tittle=None,
            author=None,
            _pageBreakQuick=1,
            encrypt=None,
        )

        self.body = []

        concepts = self.invoice.concept_set.all().order_by('-amount')
        if concepts:
            table_cont = []
            pos = 1
            for cncpt in concepts:
                description = Paragraph(cncpt.description,
                                        self.paragraph_estile_1)
                table_cont.append([
                    pos, description, cncpt.quantity, cncpt.amount,
                    cncpt.amount * cncpt.quantity
                ])
                pos += 1
            self.body.append(
                Table(table_cont,
                      style=self.table_style,
                      colWidths=(1.2 * cm, 13.1 * cm, 0.8 * cm, 1.6 * cm,
                                 2 * cm)))

        self.sheet_style.build(self.body)
예제 #4
0
    def multiBuild(self,
                   story,
                   onFirstPage=_doNothing,
                   onLaterPages=_doNothing,
                   canvasmaker=Canvas,
                   maxPasses=10,
                   **buildKwds):
        """Makes multiple passes until all indexing flowables
        are happy.

        Returns number of passes"""
        self._calc()  # in case we changed margins sizes etc
        frameT = Frame(self.leftMargin,
                       self.bottomMargin,
                       self.width,
                       self.height,
                       id='normal')

        self.addPageTemplates([
            PageTemplate(id='First',
                         frames=frameT,
                         onPage=onFirstPage,
                         pagesize=pagesizes.A4),
            PageTemplate(id='Later',
                         frames=frameT,
                         onPage=onLaterPages,
                         pagesize=pagesizes.A4)
        ])
        if onFirstPage is _doNothing and hasattr(self, 'onFirstPage'):
            self.pageTemplates[0].beforeDrawPage = self.onFirstPage
        if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'):
            self.pageTemplates[1].beforeDrawPage = self.onLaterPages
        self._indexingFlowables = []
        # scan the story and keep a copy
        for thing in story:
            if thing.isIndexing():
                self._indexingFlowables.append(thing)

        # better fix for filename is a 'file' problem
        self._doSave = 0
        passes = 0
        mbe = []
        self._multiBuildEdits = mbe.append
        while 1:
            passes += 1
            if self._onProgress:
                self._onProgress('PASS', passes)
            if verbose:
                sys.stdout.write('building pass ' + str(passes) + '...')

            for fl in self._indexingFlowables:
                fl.beforeBuild()

            # work with a copy of the story, since it is consumed
            tempStory = story[:]
            self.build(tempStory, **buildKwds)
            # self.notify('debug',None)

            for fl in self._indexingFlowables:
                fl.afterBuild()

            happy = self._allSatisfied()

            if happy:
                self._doSave = 0
                self.canv.save()
                break
            if passes > maxPasses:
                raise IndexError("Index entries not resolved after %d passes" %
                                 maxPasses)

            # work through any edits
            while mbe:
                e = mbe.pop(0)
                e[0](*e[1:])

        del self._multiBuildEdits
        if verbose:
            print('saved')
        return passes
예제 #5
0
    def page_layouts(self, pagesize, cardsize, margins, spacing):
        """
            Generate page templates for front/back sides of cards

            @param pagesize: the page size, tuple (w, h)
            @param cardsize: the card size, tuple (w, h)
            @param margins: the page margins, tuple (N, E, S, W)
            @param spacing: the spacing between cards, tuple (H, V)

            - all sizes in points (72 points per inch)
        """

        pagewidth, pageheight = pagesize
        cardwidth, cardheight = cardsize

        topmargin, leftmargin = margins[0], margins[3]

        hspacing, vspacing = spacing

        # Y-position (from page bottom) of first card row
        y0 = pageheight - topmargin - cardheight

        # X-position of first card in a row
        # - front from the left, back from the right
        # - actual page width differs between printers, so we may need
        #   to add a parameter to account for this horizontal shift (TODO)
        x0_front = leftmargin
        x0_back = pagewidth - leftmargin - cardwidth  # + hshift

        fframes, bframes = [], []
        for i in range(self.rows_per_page):

            # Y-position of current row
            y = y0 - i * (vspacing + cardheight)

            # Add frames for cards in this row
            for j in range(self.cards_per_row):

                # Front
                fframes.append(
                    Frame(
                        x0_front + j * (cardwidth + hspacing),
                        y,
                        cardwidth,
                        cardheight,
                        topPadding=0,
                        rightPadding=0,
                        bottomPadding=0,
                        leftPadding=0,
                    ))

                # Back
                bframes.append(
                    Frame(
                        x0_back - j * (cardwidth + hspacing),
                        y,
                        cardwidth,
                        cardheight,
                        topPadding=0,
                        rightPadding=0,
                        bottomPadding=0,
                        leftPadding=0,
                    ))

        # Generate and return the page templates
        return [
            PageTemplate(id="Front", frames=fframes),
            PageTemplate(id="Back", frames=bframes),
        ]
예제 #6
0
def generate_pdf(term_dictionary, selected_properties, selected_terms,
                 file_name):

    # create a list of lists for data to be added to PDF table
    data = []
    # append properties to first row of PDF table
    data.append(selected_properties)
    for item in selected_terms:
        row = []
        for property in selected_properties:
            row.append(term_dictionary[item][property])
        data.append(row)

    def header(canvas, c):
        canvas.saveState()

    c = BaseDocTemplate(file_name, pagesize=landscape(letter))
    frame = Frame(c.leftMargin,
                  c.bottomMargin,
                  c.width,
                  c.height - 2 * mm,
                  id='normal')
    template = PageTemplate(id='term_table', frames=frame, onPage=header)
    c.addPageTemplates([template])

    styles = getSampleStyleSheet()
    styles = call_stylesheet()

    story = []
    spacer = Spacer(1, 10 * mm)

    # add table
    header = []
    cell = ['BIDS Terms']
    # header.append(cell)
    colWidth = ()
    numberOfColumns = len(selected_properties)
    for i in range(1, numberOfColumns):
        cell.append([''])
        # colWidth = colWidth + (len(selected_properties[i]))
    header.append(cell)

    t = Table(header,
              colWidths=numberOfColumns * [(7.5 / numberOfColumns) * inch],
              style=[('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                     ('SPAN', (0, 0), (-1, 0)),
                     ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                     ('BACKGROUND', (0, 0), (-1, 0), '#3498DB')])
    story.append(t)

    table_style = []
    # creates alternating colors in table rows
    for i, row in enumerate(data):
        if i % 2 == 0:
            table_style.append(('BACKGROUND', (0, i), (-1, i), '#D6EAF8'))

    t = Table(data,
              repeatRows=1,
              colWidths=numberOfColumns * [(12 / numberOfColumns) * inch],
              style=[('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                     ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                     ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold')])
    # t.wrapOn(c,landscape(letter),landscape(letter))
    t.setStyle(table_style)
    story.append(t)
    # story.append(spacer)

    c.build(story)
예제 #7
0
 def _end_document(self):
     template = PageTemplate('normal', [self.tframe])
     self.doc.addPageTemplates(template)
     self.doc.build(self.elements)
예제 #8
0
def _create_renewal(renewal_buffer, approval, proposal):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame],
                                       onPage=_create_approval_header)

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

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

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

    elements = []

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

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

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

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

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

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

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

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'As a reminder, the Commercial Operator Handbook outlines the conditions of your licence. '
            'The current handbook is available online at the {} website:'.
            format(settings.DEP_NAME), styles['Left']))

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

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

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

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return renewal_buffer
예제 #9
0
                if path.endswith(".yml") or path.endswith(".yaml"):
                    yaml_files.add(path)
    if xml_files:
        with open("index.yaml", "r") as stream:
            index = yaml.safe_load(stream)
        for xml_file in xml_files:
            parse_xml(xml_file)
    for yaml_file in yaml_files:
        parse_yaml(yaml_file)
    monsters_sorted = sorted(monsters.keys())
    # Process monsters dict
    for name in monsters_sorted:
        monster = monsters[name]
        # CSV
        if args.csv:
            csv_write_row(monster)
        # PDF
        elif args.pdf:
            pdf_create_page(monster)
        # YAML
        elif args.yaml:
            yaml_write(monster)
        # Plain
        else:
            plain_write(monster)
    # Complete PDF document creation
    if args.pdf:
        pages.append(PageTemplate(frames=frames))
        doc.addPageTemplates(pages)
        doc.build(elements)
예제 #10
0
def _create_approval(approval_buffer, approval, proposal, copied_to_permit,
                     user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame],
                                       onPage=_create_approval_header)

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

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

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

    elements = []

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

    #Organization details

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

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

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

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

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

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

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

    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 = []

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

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

    elements.append(KeepTogether(delegation))

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

    doc.build(elements)

    return approval_buffer
예제 #11
0
def _create_approval_cols(approval_buffer, approval, proposal,
                          copied_to_permit, user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame],
                                       onPage=_create_approval_header)

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

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

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

    elements = []

    #Organization details

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

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

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

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

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

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements.append(KeepTogether(delegation))

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

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

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

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

    elements += _layout_extracted_fields(approval.extracted_fields)

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

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

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

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

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    park_data = []
    for p in approval.current_proposal.selected_parks_activities_pdf:
        activities_str = []
        for ac in p['activities']:
            activities_str.append(ac.encode('UTF-8'))
        access_types_str = []
        if 'access_types' in p:
            for at in p['access_types']:
                access_types_str.append(at.encode('UTF-8'))
        activities_str = str(activities_str).strip('[]').replace('\'', '')
        access_types_str = str(access_types_str).strip('[]').replace('\'', '')

        activities_str = activities_str if access_types_str == '' else access_types_str + ', ' + activities_str

        park_data.append([
            Paragraph(_format_name(p['park']), styles['BoldLeft']),
            Paragraph(activities_str.strip().strip(','),
                      styles['Left'])  # remove last trailing comma
        ])

    if park_data:
        t = Table(park_data,
                  colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                  style=box_table_style)
    elements.append(t)

    # Schedule 2
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(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
예제 #12
0
파일: print.py 프로젝트: mediaotg/mediaPlan
    def publicationReport(self, plan, publication, ads):
        styles = getSampleStyleSheet()
        Elements = []
        doc = BaseDocTemplate(self.buffer)
        column_gap = 1 * inch
        templates = []
        top = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    rightPadding=column_gap / 2,
                    showBoundary=0)
        left = Frame(doc.leftMargin,
                     doc.bottomMargin,
                     doc.width,
                     doc.height - ((plan.designs.count() * inch) + 1 * inch),
                     showBoundary=0)
        designs = Frame(doc.leftMargin + doc.width / 2,
                        doc.bottomMargin,
                        doc.width / 2,
                        doc.height - .5 * inch,
                        showBoundary=0)
        columns = []
        columns.append(top)
        columns.append(designs)
        columns.append(left)
        templates.append(PageTemplate(frames=columns, id="columns"))
        doc.addPageTemplates(templates)

        styles.add(
            ParagraphStyle(name='line',
                           parent=styles['BodyText'],
                           spaceBefore=0))
        styles.add(
            ParagraphStyle(name='campaign-name',
                           parent=styles['h4'],
                           spaceBefore=0,
                           spaceAfter=0,
                           fontName='Helvetica-Bold'))

        image = Image(
            '/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/static/img/mediaotg-small.png',
            122.25, 31.75)
        image.hAlign = 'LEFT'
        Elements.append(Spacer(width=0, height=.25 * inch))
        Elements.append(image)
        Elements.append(Spacer(width=0, height=.5 * inch))

        Elements.append(Paragraph(str(publication.name), styles['line']))
        Elements.append(Paragraph(str(publication.contactName),
                                  styles['line']))
        Elements.append(Spacer(width=0, height=.25 * inch))

        Elements.append(Paragraph('Plan no: ' + str(plan.pk), styles['line']))
        Elements.append(Paragraph(str(plan.name), styles['campaign-name']))
        client = plan.client
        if plan.client.parent != None:
            client += ' - ' + plan.client.parent
        Elements.append(Paragraph(str(client), styles['line']))
        Elements.append(
            Paragraph('Created: ' + f'{plan.created_at:%b %d, %Y}',
                      styles['line']))
        Elements.append(FrameBreak())

        designList = []
        for design in plan.designs.all():
            tempImage = ''
            if design.thumbnail is not None:
                print('WIDTH: ' + str(design.thumbnail.image.width))
                tempImage = Image(
                    "/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/"
                    + design.thumbnail.image.url,
                    design.thumbnail.image.width / 20,
                    design.thumbnail.image.height / 20)
            designList.append([design.name, tempImage])
        Elements.append(Spacer(width=0, height=.25 * inch))
        designList.insert(0, ['Designs', ''])
        wh_table = Table(designList, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)
        Elements.append(FrameBreak())

        adsList = []
        for ad in ads:
            deadline = ''
            if hasattr(ad, 'week'):
                deadline = str(ad.week.start) + ' - ' + str(ad.week.end)
            else:
                deadline = ad.deadline
            adsList.append([
                ad.rate.rateName, deadline, ad.design,
                '$' + ('%.2f' % int(ad.rate.price))
            ])
        Elements.append(Spacer(width=0, height=.25 * inch))
        adsList.insert(0, ['Ads', '', '', ''])
        wh_table = Table(adsList, colWidths=[1.05 * inch])
        wh_table._argW[1] = 3 * inch

        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)

        doc.build(Elements)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
예제 #13
0
파일: print.py 프로젝트: mediaotg/mediaPlan
    def planReport(self, table_data, title, plan):
        styles = getSampleStyleSheet()
        Elements = []
        doc = BaseDocTemplate(self.buffer)
        column_gap = 1 * inch
        templates = []
        top = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    rightPadding=column_gap / 2,
                    showBoundary=0)
        left = Frame(doc.leftMargin,
                     doc.bottomMargin,
                     doc.width,
                     doc.height - ((plan.designs.count() * inch)),
                     showBoundary=0)
        designs = Frame(doc.leftMargin + doc.width / 2,
                        doc.bottomMargin,
                        doc.width / 2,
                        doc.height - .5 * inch,
                        showBoundary=0)
        columns = []
        # tops = []
        columns.append(top)
        columns.append(designs)
        columns.append(left)
        # templates.append(PageTemplate(frames=tops, id="top"))
        templates.append(PageTemplate(frames=columns, id="columns"))
        doc.addPageTemplates(templates)

        styles.add(
            ParagraphStyle(name='line',
                           parent=styles['BodyText'],
                           spaceBefore=0))
        styles.add(
            ParagraphStyle(name='campaign-name',
                           parent=styles['h4'],
                           spaceBefore=0,
                           spaceAfter=0,
                           fontName='Helvetica-Bold'))
        image = Image(
            'http://mediaplan.herokuapp.com/static/img/mediaotg-small.png',
            122.25, 31.75)
        image.hAlign = 'LEFT'
        Elements.append(Spacer(width=0, height=.25 * inch))
        Elements.append(image)
        Elements.append(Spacer(width=0, height=.5 * inch))
        Elements.append(Paragraph('Plan no: ' + str(plan.pk), styles['line']))
        Elements.append(Paragraph(str(plan.name), styles['campaign-name']))
        client = plan.client
        if plan.client.parent != None:
            client += ' - ' + plan.client.parent
        Elements.append(Paragraph(str(client), styles['line']))
        Elements.append(
            Paragraph('Created: ' + f'{plan.created_at:%b %d, %Y}',
                      styles['line']))
        Elements.append(FrameBreak())

        designList = []
        for design in plan.designs.all():
            tempImage = ''
            if design.thumbnail is not None:
                print('WIDTH: ' + str(design.thumbnail.image.width))
                tempImage = Image(
                    "/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/"
                    + design.thumbnail.image.url,
                    design.thumbnail.image.width / 20,
                    design.thumbnail.image.height / 20)
            designList.append([design.name, tempImage])
        Elements.append(Spacer(width=0, height=.25 * inch))
        designList.insert(0, ['Designs', ''])
        wh_table = Table(designList, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)

        Elements.append(FrameBreak())
        for table in table_data:
            Elements.append(Spacer(width=0, height=.25 * inch))
            wh_table = Table(table['table'], colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        if plan.full_ads.count() > 0:
            fullList = []
            fullTotal = 0
            for ad in plan.full_ads.all():
                fullList.append([
                    ad.rate.publication.name, ad.rate.rateName, ad.deadline,
                    ad.design, '$' + ('%.2f' % int(ad.rate.price))
                ])
                fullTotal += int(ad.rate.price)
            Elements.append(Spacer(width=0, height=.25 * inch))
            fullList.insert(
                0,
                ['Full Campaign', '', '', '', '$' + ('%.2f' % int(fullTotal))])
            wh_table = Table(fullList, colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        if plan.expenses.count() > 0:
            extraList = []
            extraTotal = 0
            for ad in plan.expenses.all():
                extraList.append([
                    ad.name, '', ad.deadline, '',
                    '$' + ('%.2f' % int(ad.total))
                ])
                extraTotal += int(ad.total)
            Elements.append(Spacer(width=0, height=.25 * inch))
            extraList.insert(0, [
                'Additional Expenses', '', '', '', '$' +
                ('%.2f' % int(extraTotal))
            ])
            wh_table = Table(extraList, colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        Elements.append(Spacer(width=0, height=.25 * inch))
        totals = [['Totals']]
        weekly = 0
        for ad in plan.weekly_ads.all():
            weekly += int(ad.rate.price)
        totals.append(['Weeklys', '$' + ('%.2f' % int(weekly))])
        wh_table = Table(totals, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        wh_table.hAlign = 'RIGHT'
        Elements.append(wh_table)

        doc.build(Elements)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
예제 #14
0
def repo_page_template():
    firstFrame = [
        Frame(xm,
              ym + 25 * yc,
              7 * xc,
              3 * yc,
              id='logo',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 7 * xc,
              ym + 25 * yc,
              9 * xc,
              3 * yc,
              id='title',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 16 * xc,
              ym + 27 * yc,
              4 * xc,
              1 * yc,
              id='date',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 16 * xc,
              ym + 25 * yc,
              4 * xc,
              2 * yc,
              id='author',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 23 * yc,
              5 * xc,
              yc,
              id='part no.',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 5 * xc,
              ym + 23 * yc,
              10 * xc,
              yc,
              id='part description',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 15 * xc,
              ym + 23 * yc,
              5 * xc,
              yc,
              id='date',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 22 * yc,
              5 * xc,
              yc,
              id='step name',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 5 * xc,
              ym + 22 * yc,
              15 * xc,
              yc,
              id='step description',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 21 * yc,
              3 * xc,
              yc,
              id='hostid',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 3 * xc,
              ym + 21 * yc,
              5 * xc,
              yc,
              id='host',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 8 * xc,
              ym + 21 * yc,
              12 * xc,
              yc,
              id='name',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 20 * yc,
              10 * xc,
              yc,
              id='LO limits',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 10 * xc,
              ym + 20 * yc,
              10 * xc,
              yc,
              id='Hi limits',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 19 * yc,
              5 * xc,
              yc,
              id='evaluation label',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm + 5 * xc,
              ym + 19 * yc,
              15 * xc,
              yc,
              id='evaluation time',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym + 9 * yc,
              20 * xc,
              10 * yc,
              id='graph',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0),
        Frame(xm,
              ym,
              20 * xc,
              9 * yc,
              id='table',
              leftPadding=0,
              rightPadding=0,
              topPadding=0,
              bottomPadding=0)
    ]
    return PageTemplate(id='first', frames=firstFrame, onPage=foot)
예제 #15
0
width, height = A4[1] * 127 / 360, A4[0] * 127 / 360  # A4 landscape frame,
# converted from points to mm

pagesize = (width * mm, height * mm)
F = Frame(
    0,
    0,
    width * mm,
    height * mm,
    leftPadding=.5 * inch,
    bottomPadding=.5 * inch,
    rightPadding=.5 * inch,
    topPadding=.5 * inch,
)
PT = PageTemplate(id="calendar", frames=[
    F,
])

doc = BaseDocTemplate("biocal_%4u–%02u–%02u_%u.pdf" % (by, bm, bd, year))
doc.pagesize = landscape(A4)
doc.addPageTemplates([
    PT,
])
doc.title = "%u biorhythm calendar for %4u–%02u–%02u" % (year, by, bm, bd)
elements = []

dnamelist = 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'
mnamelist = [[
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
    'Nov', 'Dec'
]]
def _create_pdf(invoice_buffer, sanction_outcome):
    MARGIN_TOP = 5
    MARGIN_BOTTOM = 5
    every_page_frame = Frame(PAGE_MARGIN, MARGIN_TOP, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - (MARGIN_TOP + MARGIN_BOTTOM), id='EveryPagesFrame',)  # showBoundary=Color(0, 1, 0))
    # every_page_frame2 = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - 2 * PAGE_MARGIN, id='EveryPagesFrame2',)  # showBoundary=Color(0, 0, 1))
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame,], )
    # every_page_template2 = PageTemplate(id='EveryPages2', frames=[every_page_frame2,], )
    doc = BaseDocTemplate(invoice_buffer, pageTemplates=[every_page_template, ], pagesize=A4,)  # showBoundary=Color(1, 0, 0))
    # doc = BaseDocTemplate(invoice_buffer, pageTemplates=[every_page_template, every_page_template2,], pagesize=A4,)  # showBoundary=Color(1, 0, 0))

    # Logo
    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    width = dpaw_header_logo_size[0]/2
    height = dpaw_header_logo_size[1]/2
    dbca_logo = Image(DPAW_HEADER_LOGO, width=width, height=height)

    # 1st page
    t1 = get_infringement_notice_table(sanction_outcome)

    # 2nd page
    title_evidential_notes = Paragraph('<strong>EVIDENTIAL NOTES:</strong>', styles['Normal'])

    # table
    col_width = [40*mm, 35*mm, 22*mm, 31*mm, 37*mm, ]
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('SPAN', (1, 0), (4, 0)),
        ('SPAN', (1, 1), (4, 1)),
        ('SPAN', (1, 2), (4, 2)),
        ('SPAN', (1, 3), (4, 3)),
        ('SPAN', (2, 5), (3, 5)),
        ('SPAN', (2, 6), (4, 6)),
    ])
    data = []
    rego = sanction_outcome.registration_number if sanction_outcome.registration_number else ''
    data.append([
        Paragraph('<strong>Registration number<br />vehicle/vessel:</strong>', styles['Normal']),
        Paragraph(get_font_str(rego), styles['Normal']),
        '', '', '',
    ])
    data.append([
        Paragraph('<strong>Make:</strong>', styles['Normal']),
        '', '', '', '',
    ])
    data.append([
        Paragraph('<strong>Model:</strong>', styles['Normal']),
        '', '', '', '',
    ])
    data.append([
        Paragraph('<strong>Type: i.e SUV etc</strong>', styles['Normal']),
        '', '', '', '',
    ])

    data.append([
        Paragraph('<strong>Photograph(s) taken:</strong>', styles['Normal']),
        YesNoCheckbox(11, 11, fontName='Helvetica'),
        Paragraph('<strong>Attached:</strong>', styles['Normal']),
        YesNoCheckbox(11, 11, fontName='Helvetica'),
        Paragraph('<strong>Number:</strong>', styles['Normal']),
    ])
    data.append([
        Paragraph('<strong>Gender:<br />Tick relevant box</strong>', styles['Normal']),
        ParagraphCheckbox('Male', styles['Normal'],),
        ParagraphCheckbox('Female', styles['Normal'], ),
        '',
        ParagraphCheckbox('Other/unknown', styles['Normal'], ),
    ])
    data.append([
        Paragraph('<strong>Identification<br />produced:</strong>', styles['Normal']),
        YesNoCheckbox(11, 11, fontName='Helvetica'),
        Paragraph('<strong>If Yes, provide details:</strong>', styles['Normal']),
        '', '',
    ])
    t2 = Table(data, style=invoice_table_style, colWidths=col_width)

    title_original_notes = Paragraph('<strong>ORIGINAL NOTES OF INCIDENT:</strong>', styles['Normal'])

    elements = []
    elements.append(dbca_logo)
    elements.append(t1)
    elements.append(PageBreak())
    elements.append(dbca_logo)
    elements.append(title_evidential_notes)
    elements.append(Spacer(0, 5*mm))
    elements.append(t2)
    elements.append(Spacer(0, 5*mm))
    elements.append(title_original_notes)
    for i in range(0, 23):
        elements.append(SolidLine(440, 0, dashed=True, wrap_height=20))
    elements.append(Spacer(0, 10*mm))
    elements.append(Paragraph('<strong>Signature:</strong>' + gap(50) + '<strong>Date:</strong>', styles['Normal']))

    doc.build(elements)
    return invoice_buffer
예제 #17
0
 def __init__(self, filename, **kw):
     frame1 = platypus.Frame(inch, 5.6*inch, 6*inch, 5.2*inch,id='F1')
     frame2 = platypus.Frame(inch, inch, 6*inch, 4.5*inch, showBoundary=1,id='F2')
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self,filename,**kw)
     self.addPageTemplates(PageTemplate('normal',[frame1,frame2],framePage))
예제 #18
0
def _create_pdf(invoice_buffer, sanction_outcome):
    PAGE_MARGIN = 5 * mm
    page_frame_1 = Frame(
        PAGE_MARGIN,
        PAGE_MARGIN,
        PAGE_WIDTH - 2 * PAGE_MARGIN,
        PAGE_HEIGHT - 2 * PAGE_MARGIN,
        id='PagesFrame1',
    )  #showBoundary=Color(0, 1, 0))
    PAGE_MARGIN2 = 17 * mm
    page_frame_2 = Frame(
        PAGE_MARGIN2,
        PAGE_MARGIN2,
        PAGE_WIDTH - 2 * PAGE_MARGIN2,
        PAGE_HEIGHT - 2 * PAGE_MARGIN2,
        id='PagesFrame2',
    )  #showBoundary=Color(0, 0, 1))
    page_template_1 = PageTemplate(
        id='Page1',
        frames=[
            page_frame_1,
        ],
    )
    page_template_2 = PageTemplate(
        id='Page2',
        frames=[
            page_frame_2,
        ],
    )
    doc = BaseDocTemplate(
        invoice_buffer,
        pageTemplates=[page_template_1, page_template_2],
        pagesize=A4,
    )  # showBoundary=Color(1, 0, 0))

    # Common
    FONT_SIZE_L = 11
    FONT_SIZE_M = 10
    FONT_SIZE_S = 8

    styles = StyleSheet1()
    styles.add(
        ParagraphStyle(
            name='Normal',
            fontName='Helvetica',
            fontSize=FONT_SIZE_M,
            spaceBefore=7,  # space before paragraph
            spaceAfter=7,  # space after paragraph
            leading=12))  # space between lines
    styles.add(
        ParagraphStyle(name='BodyText', parent=styles['Normal'],
                       spaceBefore=6))
    styles.add(
        ParagraphStyle(name='Italic',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Italic'))
    styles.add(
        ParagraphStyle(name='Bold',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Bold',
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name='Right',
                       parent=styles['BodyText'],
                       alignment=TA_RIGHT))
    styles.add(
        ParagraphStyle(name='Centre',
                       parent=styles['BodyText'],
                       alignment=TA_CENTER))

    # Logo
    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    width = dpaw_header_logo_size[0] / 2
    height = dpaw_header_logo_size[1] / 2
    dbca_logo = Image(DPAW_HEADER_LOGO, width=width, height=height)

    # Table
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('SPAN', (0, 0), (1, 0)),

        # Alleged offender
        ('SPAN', (0, 1), (0, 5)),
        ('SPAN', (1, 1), (2, 1)),
        ('SPAN', (1, 2), (2, 2)),
        ('SPAN', (1, 3), (2, 3)),
        ('SPAN', (1, 4), (2, 4)),
        ('SPAN', (1, 5), (2, 5)),

        # When
        ('SPAN', (1, 6), (2, 6)),

        # Where
        ('SPAN', (1, 7), (2, 7)),

        # Alleged offence
        ('SPAN', (0, 8), (0, 9)),
        ('SPAN', (1, 8), (2, 8)),
        # ('SPAN', (1, 9), (2, 9)),
        ('SPAN', (1, 9), (2, 9)),
        # ('SPAN', (1, 10), (2, 10)),

        # Officer issuing notice
        ('SPAN', (0, 10), (0, 12)),
        ('SPAN', (1, 10), (2, 10)),
        ('SPAN', (1, 11), (2, 11)),
        ('SPAN', (1, 12), (2, 12)),

        # Date
        ('SPAN', (1, 13), (2, 13)),

        # Notice to alleged offender
        ('SPAN', (1, 14), (2, 14)),
    ])
    date_str = gap(10) + '/' + gap(10) + '/ 20'
    col_width = [
        40 * mm,
        60 * mm,
        80 * mm,
    ]

    data = []
    data.append([
        Paragraph(
            '<i>Biodiversity Conservation Act 2016</i><br /><strong><font size="'
            + str(FONT_SIZE_L) + '">Caution Notice</font></strong>',
            styles['Normal']), '',
        Paragraph(
            u'Caution<br />notice no. ' +
            get_font_str(sanction_outcome.lodgement_number), styles['Normal'])
    ])

    # Alleged offender
    offender = sanction_outcome.get_offender()
    offender_dob = offender[0].dob.strftime(
        '%d/%m/%Y') if offender[0].dob else ''
    data.append([
        Paragraph('Alleged offender', styles['Bold']),
        Paragraph('Name: Family name: ' + get_font_str(offender[0].last_name),
                  styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Given names: ' + get_font_str(offender[0].first_name),
            styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Date of Birth: ' + get_font_str(offender_dob),
            styles['Normal']), ''
    ])
    data.append([
        '',
        [
            Paragraph('<strong>or</strong><br />Body corporate name',
                      styles['Normal']),
            Spacer(1, 25)
        ], ''
    ])
    # data.append(['', [Paragraph('Address', styles['Normal']), Spacer(1, 25), Paragraph('Postcode', styles['Normal'])], ''])
    postcode = offender[0].residential_address.postcode if offender[
        0].residential_address else ''
    data.append([
        '',
        [
            Paragraph('Address: ', styles['Normal']),
            Paragraph(get_font_str(str(offender[0].residential_address)),
                      styles['Normal']),
            Paragraph('Postcode: ' + get_font_str(postcode), styles['Normal']),
        ],
        '',
    ])

    # When
    # data.append([Paragraph('When', styles['Bold']), Paragraph('Date' + date_str + gap(5) + 'Time' + gap(10) + 'am/pm', styles['Normal']), ''])
    offence_datetime = sanction_outcome.offence.offence_occurrence_datetime
    data.append([
        Paragraph('When', styles['Bold']),
        Paragraph(
            'Date: ' + get_font_str(offence_datetime.strftime('%d/%m/%Y')) +
            gap(5) + 'Time: ' +
            get_font_str(offence_datetime.strftime('%I:%M %p')),
            styles['Normal']), ''
    ])

    # Where
    # data.append([Paragraph('Where', styles['Bold']), [Paragraph('Location of offence', styles['Normal']), Spacer(1, 25)], ''])
    offence_location = sanction_outcome.offence.location
    offence_location_str = str(offence_location) if offence_location else ''
    data.append([
        Paragraph('Where', styles['Bold']),
        [
            Paragraph('Location of offence', styles['Normal']),
            Paragraph(get_font_str(offence_location_str), styles['Normal']),
            Spacer(1, 25)
        ],
        '',
    ])

    # Alleged offence
    data.append([
        Paragraph('Alleged offence', styles['Bold']),
        [
            Paragraph('Description of offence', styles['Normal']),
        ], ''
    ])  # row index: 8
    # data.append(['', rect, ''])
    # data.append(['', '?', ''])
    data.append([
        '',
        Paragraph(
            '<i>Biodiversity Conservation Act 2016 s.</i>' + gap(10) +
            'or<br /><i>Biodiversity Conservation Regulations 2018 r.</i>',
            styles['Normal']), ''
    ])

    # Officer issuing notice
    # data.append([Paragraph('Officer issuing notice', styles['Bold']), Paragraph('Name', styles['Normal']), ''])  # row index: 12
    data.append([
        Paragraph('Officer issuing notice', styles['Bold']),
        Paragraph(
            'Name: {}'.format(
                get_font_str(
                    sanction_outcome.responsible_officer.get_full_name())),
            styles['Normal']), ''
    ])  # row index: 12
    data.append(['', Paragraph('Signature', styles['Normal']), ''])
    data.append(['', Paragraph('Officer no.', styles['Normal']), ''])

    # Date
    issue_date = get_font_str(
        sanction_outcome.date_of_issue.strftime('%d/%m/%Y'))
    issue_time = get_font_str(
        sanction_outcome.time_of_issue.strftime('%I:%M %p'))
    data.append([
        Paragraph('Date', styles['Bold']),
        Paragraph('Date of notice: ' + issue_date + ' ' + issue_time,
                  styles['Normal']), ''
    ])

    # Notice to alleged offender
    body = []
    body.append(
        Paragraph(
            'It is alleged that you have committed the above offence.</p>',
            styles['Normal']))
    body.append(
        Paragraph(
            'If you object to the issue of this notice you can apply in writing to the Approved Officer at the below address for a review within 28 days after the date of this notice.',
            styles['Normal']))
    body.append(
        Paragraph(
            'Approved Officer — <i>Biodiversity Conservation Act 2016</i><br />Department of Biodiversity, Conservation and Attractions<br />Locked Bag 104<br />Bentley Delivery Centre WA 6983',
            styles['Normal']))
    data.append(
        [Paragraph('Notice to alleged offender', styles['Bold']), body, ''])

    # Create 1st table
    t1 = Table(data, style=invoice_table_style, colWidths=col_width)

    # Append tables to the elements to build
    gap_between_tables = 1.5 * mm
    elements = []
    elements.append(dbca_logo)
    elements.append(Spacer(0, 5 * mm))
    elements.append(t1)
    elements.append(NextPageTemplate([
        'Page2',
    ]))
    elements.append(PageBreak())
    elements.append(dbca_logo)
    elements.append(Spacer(0, 5 * mm))
    # ORIGINAL NOTES OF INCIDENT:
    title_original_notes = Paragraph(
        '<font size="' + str(FONT_SIZE_L) +
        '"><strong>ORIGINAL NOTES OF INCIDENT:</strong></font>',
        styles['Normal'])
    elements.append(title_original_notes)
    elements.append(Spacer(0, 10 * mm))
    for i in range(0, 25):
        elements.append(BrokenLine(170 * mm, 8 * mm))
    elements.append(
        Paragraph(
            '<font size="' + str(FONT_SIZE_L) + '"><strong>Signature: ' +
            gap(80) + 'Date:</strong></font>', styles['Normal']))

    doc.build(elements)
    return invoice_buffer
예제 #19
0
def _create_invoice(invoice_buffer, invoice):
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN + 250, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT -450 , id='EveryPagesFrame',showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 600, id='RemitFrame',showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame,remit_frame], onPage=_create_header)
    

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

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

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID',(0, 0), (-1, -1),1, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT')
        ])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    if invoice.text:
        elements.append(Paragraph(invoice.text, styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    data = [
        ['Item','Product', 'Quantity','Unit Price', 'Total']
    ]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    for item in items:
        data.append(
            [
                val,
                Paragraph(item.description, s),
                item.quantity,
                currency(item.unit_price_incl_tax),
                currency(item.line_price_before_discounts_incl_tax)
            ]
        )
        val += 1
    # Discounts
    data.append(
        [
            '',
            '',
            '',
            ''
        ]
    )
    for discount in discounts:
        data.append(
            [
                '',
                discount.offer,
                '',
                '',
                '-${}'.format(discount.amount)
            ]
        )
        val += 1
    t= Table(
            data,
            style=invoice_table_style,
            hAlign='LEFT',
            colWidths=(
            0.7 * inch,
            None,
            0.7 * inch,
            1.0 * inch,
            1.0 * inch,
            )
        )
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
        elements.append(Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))
    
    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN *1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    
    remittance = Remittance(HEADER_MARGIN,HEADER_MARGIN - 10,invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)
    
    return invoice_buffer
예제 #20
0
    def generar_comprobante(self):
        hoy = datetime.now()
        response = HttpResponse(content_type='application/pdf')
        # se crea el nombre del archivo de la descarga pdf
        pdf_name = 'comprobante_{}.pdf'.format(hoy.strftime("%Y%m%d"))
        response['Content-Disposition'] = 'inline; filename={}'.format(
            pdf_name)
        # se crea el buffer de memoria para generar el documento
        buffer = BytesIO()

        pdftam = (22 * cm, 14.5 * cm)
        # configuracion de documento base para la plantilla
        doc = BaseDocTemplate(buffer,
                              pagesize=pdftam,
                              leftMargin=1 * cm,
                              rightMargin=1 * cm,
                              topMargin=1 * cm,
                              bottomMargin=1 * cm)
        frame0 = Frame(doc.leftMargin + 2 * cm,
                       doc.bottomMargin,
                       doc.width - 2 * cm,
                       doc.height - 2.5 * cm,
                       showBoundary=1,
                       id='bordeNormal')
        doc.addPageTemplates([
            PageTemplate(id='principal',
                         frames=frame0,
                         onPage=self.__encabezado,
                         onPageEnd=self.__pie),
        ])

        story = []

        for carga in self.__cargas:
            numero_literal = NumeroLiteral()

            data0 = [['FECHA', '', '', 'Nro:', 'P{}'.format(carga.numero)],
                     [
                         '{}'.format(hoy.day), '{}'.format(hoy.month),
                         '{}'.format(hoy.year), '', ''
                     ]]

            t0 = Table(data0,
                       [1.5 * cm, 1.5 * cm, 1.5 * cm, 10 * cm, 2.9 * cm],
                       [0.8 * cm, 0.8 * cm])

            t0.setStyle(
                TableStyle([
                    ('GRID', (0, 0), (2, 1), 0.5, colors.black),
                    ('SPAN', (0, 0), (2, 0)),
                    ('FONT', (0, 0), (2, 0), 'Helvetica-Bold', 10),
                    ('VALIGN', (0, 0), (4, 1), 'MIDDLE'),
                    ('ALIGN', (0, 0), (2, 1), 'CENTER'),
                    ('ALIGN', (3, 0), (3, 1), 'RIGHT'),
                    ('FONT', (3, 0), (3, 1), 'Helvetica-Bold', 14),
                    ('FONT', (4, 0), (4, 1), 'Helvetica', 14),
                    ('SPAN', (3, 0), (3, 1)),
                    ('SPAN', (4, 0), (4, 1)),
                ]))

            data1 = [['Pagado a:', '{} {}'.format(carga.proveedor.apellidos, carga.proveedor.nombres)],
                     ['La Suma de:', Paragraph('{} 00/100 BOLIVIANOS.'.format(
                         numero_literal.main(int(carga.liquido_pagable))))],
                     ['Por Concepto:',
                      'CARGA MINERALIZADA: P{} - {} - COT:{}'.format(carga.numero, carga.created.strftime("%d/%m/%Y"), int(carga.cotizacion))],
                     ['', 'TMH:{} - HUM%:{} - TMS:{} - LEY:{} -  Fi.Rec.:{} - V.REP:{}'.format(
                         carga.peso_neto_tn, int(carga.h2o), carga.tms_pagar, carga.au, carga.finos_gr_recup, int(carga.valor_reposicion))],
                     ['', 'PP:{} - ANT:{} - EQP:{} - BAL:{} - VOL:{} - LAB:{} DSC:{} - V.DSC:{}'.format(
                         int(carga.penalizacion_cu_soluble), int(
                             carga.anticipo), int(carga.equipo_pesado),
                         int(carga.balanza), int(carga.volqueta), int(carga.analisis_laboratorio), int(carga.otros_descuentos + carga.retencion_acuerdo), int(carga.penalizacion_cu_soluble + carga.anticipo + carga.equipo_pesado + carga.balanza + carga.volqueta + \
                            carga.analisis_laboratorio + carga.otros_descuentos + carga.retencion_acuerdo))],
                     ]
            t1 = Table(data1, [3.2 * cm, 14.2 * cm],
                       [0.6 * cm, 1.2 * cm, 0.6 * cm, 0.6 * cm, 0.6 * cm])

            t1.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (1, 0), 'MIDDLE'),
                    ('VALIGN', (0, 1), (4, 2), 'TOP'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                    ('FONT', (0, 0), (0, 4), 'Helvetica-Bold', 10),
                ]))

            data2 = [
                [
                    'Bs:', '{}'.format(numero_decimal(carga.liquido_pagable)),
                    ''
                ],
                ['Efectivo:', '', ''],
                ['Cheque No.:', '', ''],
                ['Banco:', '', ''],
                ['Cuenta Contable:', '', 'Firma Beneficiario'],
                ['', '', 'C.I./NIT:'],
            ]

            t2 = Table(data2, [3.2 * cm, 5.5 * cm, 8.7 * cm], 6 * [0.6 * cm])

            t2.setStyle(
                TableStyle([
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                    ('LINEBEFORE', (2, 0), (2, 6), 1, colors.black),
                    ('ALIGN', (2, 4), (2, 5), 'CENTER'),
                    ('RIGHTPADDING', (2, 5), (2, 5), 100),
                    ('FONT', (0, 0), (0, 4), 'Helvetica-Bold', 10),
                ]))

            story.append(t0)
            story.append(Spacer(0, 5))
            story.append(t1)
            story.append(Spacer(0, 5))
            story.append(t2)
            story.append(PageBreak())

        doc.build(story)
        pdf = buffer.getvalue()
        buffer.close()
        response.write(pdf)
        return response
예제 #21
0
        def go(doc, Story, outputpath):
            ## title page template

            titleframe = Frame(
                x1=doc.leftMargin,
                y1=doc.height / 2,
                width=doc.width,
                height=doc.height * .4,
            )

            subtitleframe = Frame(
                x1=doc.leftMargin,
                y1=doc.height / 2 - doc.topMargin,
                width=doc.width,
                height=doc.height * 0.4,
            )

            ## scan page template
            text_width = doc.width * 0.5
            text_height = doc.height * 0.35

            textframe = Frame(x1=doc.leftMargin,
                              y1=PAGE_HEIGHT - doc.topMargin - text_height,
                              width=text_width,
                              height=text_height,
                              id='textframe')
            overviewmapframe = Frame(x1=doc.leftMargin + doc.width * 0.5,
                                     y1=PAGE_HEIGHT - doc.topMargin -
                                     text_height,
                                     width=doc.width - text_width,
                                     height=text_height,
                                     id='overviewmapframe')
            xrfframe = Frame(x1=doc.leftMargin * 0.5,
                             y1=doc.bottomMargin * 0.8,
                             width=doc.width + doc.leftMargin,
                             height=doc.height - text_height,
                             id='xrfframe')

            ## 2-scan comparison page template

            def makecomparisontemplate(num_columns):
                margin = 1 - 0.01
                header_height = doc.height * 0.1 * margin
                subheader_height = doc.height * 0.1 * margin
                column_height = (doc.height - header_height -
                                 subheader_height) * margin
                column_width = (doc.width / (num_columns)) * margin

                frames = []

                frames.append(
                    Frame(x1=doc.leftMargin,
                          y1=PAGE_HEIGHT - doc.topMargin - header_height,
                          width=doc.width,
                          height=header_height,
                          id='headerframe'))
                for n in range(num_columns):
                    frames.append(
                        Frame(x1=doc.leftMargin + n * column_width,
                              y1=PAGE_HEIGHT - doc.topMargin - header_height -
                              subheader_height,
                              width=column_width,
                              height=subheader_height,
                              id='subheader_' + str(n + 1)))

                    frames.append(
                        Frame(x1=doc.leftMargin + n * column_width,
                              y1=doc.bottomMargin,
                              width=column_width,
                              height=doc.height - header_height -
                              subheader_height,
                              id='headerframe_' + str(n + 1)))
                return frames

            doc.addPageTemplates([
                PageTemplate(id='TitlePage',
                             frames=[titleframe, subtitleframe],
                             onPage=FirstPage),
                PageTemplate(id='ScanPage',
                             frames=[textframe, overviewmapframe, xrfframe],
                             onPage=myLaterPages),
                PageTemplate(id='Comparison_2',
                             frames=makecomparisontemplate(2),
                             onPage=myLaterPages),
                PageTemplate(id='Comparison_3',
                             frames=makecomparisontemplate(3),
                             onPage=myLaterPages),
                PageTemplate(id='Comparison_4',
                             frames=makecomparisontemplate(4),
                             onPage=myLaterPages)
            ])
            doc.build(Story)
예제 #22
0
파일: pdf.py 프로젝트: tawazz/ledger
def _create_invoice(invoice_buffer, invoice):
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 430,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

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

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

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'GST', 'Amount']]
    val = 1
    for item in items:
        data.append([
            val,
            Paragraph(item.description, styles['Normal']), item.quantity,
            '${}'.format(item.line_price_before_discounts_excl_tax),
            '${}'.format(item.line_price_before_discounts_incl_tax -
                         item.line_price_before_discounts_excl_tax),
            '${}'.format(item.line_price_before_discounts_incl_tax)
        ])
        val += 1
    # Discounts
    data.append(['', '', '', '', '', ''])
    for discount in discounts:
        data.append(
            ['', discount.offer, '', '', '', '-${}'.format(discount.amount)])
        val += 1
    t = Table(data, style=invoice_table_style, hAlign='LEFT')
    t._argW[1] = 3.4 * inch
    t._argW[2] = 0.7 * inch
    for x in range(3, 6):
        t._argW[x] = 1.0 * inch
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    elements.append(
        Paragraph(
            'Your application cannot be processed until payment is received.',
            styles['Left']))

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

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    remittance = Remittance(HEADER_MARGIN, HEADER_MARGIN - 10, invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
예제 #23
0

dumpset("Unique across a book", books)
document.append(PageBreak())
dumpset("Unique across a chapter", chapters)
document.append(PageBreak())
dumpset("Unique across a section", sections)

# build pdf output
doc = BaseDocTemplate("out_completeunique.pdf",
                      pagesize=pagesizes.letter,
                      topMargin=margin,
                      leftMargin=margin,
                      bottomMargin=margin,
                      rightMargin=margin)

# make default two-column output
frame1 = Frame(doc.leftMargin,
               doc.bottomMargin,
               col_width,
               doc.height,
               id='col1')
frame2 = Frame(doc.leftMargin + col_width + margin,
               doc.bottomMargin,
               col_width,
               doc.height,
               id='col2')
doc.addPageTemplates([PageTemplate(id='twocolumn', frames=[frame1, frame2])])

doc.build(document)
예제 #24
0
from reportlab.lib.colors import black, green, red, brown,blueviolet, pink, blue,white
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Frame, PageTemplate
styles = getSampleStyleSheet()

doc = SimpleDocTemplate("json_table.pdf", pagesize=letter)
frame = Frame(0, 10, 650, 780, id='col1', showBoundary=0)
Page = PageTemplate(id='col1', frames=[frame])
doc.addPageTemplates([Page])

f = open("sample2.json", "r")
import json
# st = f.read()
# print(st)
json_file = json.load(f)
text = []
col_span = []
width = []
elements = []

for key in json_file:
    head = []
    col = []
    body = []
    colbody = []
    # w = []

    for x in key["header"]:
예제 #25
0
from reportlab.platypus import (BaseDocTemplate, Frame, Paragraph,
                                NextPageTemplate, PageBreak, PageTemplate,
                                Image, Table, TableStyle, Spacer)
#from rotatedtext import verticalText

document = BaseDocTemplate('Vertical.pdf')

Elements = []

titleFrame_1 = Frame(0.5 * inch,
                     0.75 * inch,
                     7 * inch,
                     9 * inch,
                     id='col1',
                     showBoundary=0)
titleTemplate_1 = PageTemplate(id='OneCol', frames=titleFrame_1)
document.addPageTemplates([titleTemplate_1])

cw = [1.2 * inch] + [1 * inch] * 6
rh = [0.25 * inch] + [.6 * inch] + [0.25 * inch] * 7

data = [
    ['Some', 'Reporting', '', 'Data', '', 'Here', ''],
    [
        '',
        verticalText('Ve'),
        verticalText('Text'),
        verticalText('Vertical'),
        verticalText('Text'),
        verticalText('Vertical'),
        verticalText('Text')
예제 #26
0
 def create(self):
     self.template_obj = json.load(open(self.__template_path))
     self.pathToImage = self.template_obj['logo'].get('path')
     self.__doc = BaseDocTemplate(
         self.report_path + self.name,
         leftMargin=self.template_obj["margins"].get('left'),
         rightMargin=self.template_obj["margins"].get('right'),
         topMargin=self.template_obj["margins"].get('top'),
         bottomMargin=self.template_obj["margins"].get('bottom'),
         showBoundary=0)
     self.heading_frame = Frame(self.__doc.leftMargin,
                                self.__doc.height / 2,
                                self.__doc.width,
                                self.__doc.topMargin,
                                id='header')
     self.layer_description_frame = Frame(self.__doc.leftMargin,
                                          1 * self.__doc.height -
                                          self.__doc.topMargin - 600,
                                          self.__doc.width,
                                          600,
                                          id='layer')
     self.graph_frame = Frame(self.__doc.leftMargin / 2,
                              1 * self.__doc.height / 3 - 40,
                              self.__doc.width + self.__doc.leftMargin,
                              self.__doc.height / 2,
                              id='graph')
     self.map_frame = Frame(self.__doc.leftMargin,
                            1 * self.__doc.height / 3 - 90,
                            self.__doc.width,
                            self.__doc.height / 2,
                            id='map')
     self.legend_frame = Frame(self.__doc.leftMargin,
                               1 * self.__doc.height - 250,
                               self.__doc.width,
                               80,
                               id='legend')
     self.textarea_frame = Frame(self.__doc.leftMargin,
                                 self.__doc.bottomMargin + 10,
                                 self.__doc.width,
                                 self.__doc.height / 1.5,
                                 id='textarea')
     # self.legend_frame = Frame(self.__doc.leftMargin,1 * self.__doc.height / 3 - 50, self.__doc.width,
     # 							70 , id='legend')
     self.graph_description = Frame(self.__doc.leftMargin,
                                    self.__doc.bottomMargin * 1.5,
                                    self.__doc.width,
                                    self.__doc.height / 3 -
                                    self.__doc.bottomMargin * 1.5 - 25,
                                    id='graph_desc')
     self.content_descriptor = Frame(self.__doc.width / 2 - 70,
                                     self.__doc.bottomMargin * 1.5 + 130,
                                     140,
                                     30,
                                     id='desc')
     self.title_frame = Frame(self.__doc.leftMargin,
                              self.__doc.height - self.__doc.topMargin - 10,
                              self.__doc.width,
                              70,
                              id='title')
     self.firstPage_frame = Frame(self.__doc.leftMargin,
                                  self.__doc.bottomMargin * 3,
                                  self.__doc.width,
                                  self.__doc.bottomMargin * 2)
     self.firstPage_footer = Frame(
         self.__doc.leftMargin * 2, self.__doc.bottomMargin,
         self.__doc.width - self.__doc.leftMargin * 2, 50)
     self.__doc.addPageTemplates([
         PageTemplate(id='first_page',
                      frames=[self.firstPage_frame, self.firstPage_footer],
                      onPage=Header_class.Heading(
                          self.__doc,
                          self.template_obj).heading_first_page),
         PageTemplate(id='heading',
                      frames=self.heading_frame,
                      onPage=Header_class.Heading(
                          self.__doc, self.template_obj).heading),
         PageTemplate(id='graph',
                      frames=[
                          self.title_frame, self.layer_description_frame,
                          self.graph_frame, self.graph_description
                      ],
                      onPageEnd=Header_class.Heading(
                          self.__doc, self.template_obj).heading),
         PageTemplate(id='map',
                      frames=[
                          self.title_frame, self.layer_description_frame,
                          self.map_frame, self.legend_frame,
                          self.graph_description
                      ],
                      onPageEnd=Header_class.Heading(
                          self.__doc, self.template_obj).heading),
         PageTemplate(
             id='text',
             frames=[self.title_frame, self.layer_description_frame],
             onPageEnd=Header_class.Heading(self.__doc,
                                            self.template_obj).heading),
         PageTemplate(id='image',
                      frames=[
                          self.title_frame, self.layer_description_frame,
                          self.map_frame
                      ],
                      onPageEnd=Header_class.Heading(
                          self.__doc, self.template_obj).heading)
     ])
예제 #27
0
    def __init__(self, aDocInfo, aStyleSheet):
        self.docInfo = aDocInfo
        self.style = aStyleSheet

        if "pageOrientation" in self.docInfo:
            self.orientation = self.docInfo["pageOrientation"]
        else:
            self.orientation = "portrait"

        if "pageSize" in self.docInfo:
            self.pageSize = self.docInfo["pageSize"]
        else:
            self.pageSize = A4

        if isinstance(self.pageSize, list):
            if len(self.pageSize) > 1:
                self.pageRect = [self.pageSize[0], self.pageSize[1]]
        else:
            self.pageRect = \
                landscape(self.pageSize) \
                if self.orientation == "landscape" \
                else portrait(self.pageSize)

        self.doc = DocTemplateWithToc('',
                                      outputfilepagesize=self.pageRect,
                                      leftMargin=self.style["marginL"],
                                      rightMargin=self.style["marginR"],
                                      topMargin=self.style["marginT"],
                                      bottomMargin=self.style["marginB"])

        portraitTempl = PageTemplate(id="portrait",
                                     frames=Frame(
                                         0,
                                         0,
                                         self.pageRect[0],
                                         self.pageRect[1],
                                         leftPadding=self.style["marginL"],
                                         bottomPadding=self.style["marginB"],
                                         rightPadding=self.style["marginR"],
                                         topPadding=self.style["marginT"]),
                                     onPageEnd=self.drawDecoration,
                                     pagesize=self.pageRect)
        self.doc.addPageTemplates(portraitTempl)

        landscapeTempl = PageTemplate(id="landscape",
                                      frames=Frame(
                                          0,
                                          0,
                                          self.pageRect[0],
                                          self.pageRect[1],
                                          leftPadding=self.style["marginL"],
                                          bottomPadding=self.style["marginB"],
                                          rightPadding=self.style["marginR"],
                                          topPadding=self.style["marginT"]),
                                      onPageEnd=self.drawDecoration,
                                      pagesize=self.pageRect)
        self.doc.addPageTemplates(landscapeTempl)

        self.doc.setDefaultTemplate(self.orientation)

        self.decorationItems = []
예제 #28
0
def _create_licence(licence_buffer, licence, application):
    '''
    Creates licence summary and purpose details for licence.
    '''
    def _create_licence_purpose(elements, selected_activity, issued_purpose):
        '''
        Creates the licence purpose details per page available on the activity.
        '''

        # delegation holds the dates, licencee and issuer details.
        delegation = []
        sequence = purpose.purpose_sequence
        licence_display = '{0}-{1}-{2}'.format(licence.licence_number,
                                               sequence,
                                               issued_purpose.purpose.code)
        licence_purpose = issued_purpose.purpose.name
        elements.append(
            Paragraph(licence_purpose.upper(),
                      styles['InfoTitleVeryLargeCenter']))
        elements.append(
            Paragraph(
                'Regulation {}, Biodiversity Conservation Regulations 2018'.
                format(issued_purpose.purpose.regulation), styles['Center']))

        # applicant details
        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        if application.applicant_type \
                == application.APPLICANT_TYPE_ORGANISATION:
            address = application.org_applicant.address
            pass
        elif application.applicant_type == application.APPLICANT_TYPE_PROXY:
            address = application.proxy_applicant.residential_address
            pass
        else:
            # applic.applicant_type == application.APPLICANT_TYPE_SUBMITTER
            address = application.submitter.residential_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('Licence Number', styles['BoldLeft']),
                Paragraph('Licence Holder', styles['BoldLeft']),
                Paragraph('Address', styles['BoldLeft'])
            ], [Paragraph(licence_display, styles['Left'])] + [
                Paragraph(licence.current_application.applicant,
                          styles['Left'])
            ] + address_paragraphs]],
                  colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                  style=licence_table_style))

        # dates
        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('Date Valid From', styles['BoldLeft']),
            Paragraph('Date of Expiry', styles['BoldLeft'])
        ]
        date_values = [
            Paragraph(issued_purpose.issue_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.start_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.expiry_date.strftime('%d/%m/%Y'),
                      styles['Left'])
        ]

        if issued_purpose.is_reissued:
            date_headings.insert(
                0, Paragraph('Original Date of Issue', styles['BoldLeft']))
            date_values.insert(
                0, Paragraph(issued_purpose.original_issue_date,
                             styles['Left']))

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

        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        elements.append(KeepTogether(delegation))

        # species
        species_ids = issued_purpose.purpose.get_species_list
        if species_ids:
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('SPECIES', styles['BoldLeft']))
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            species = LicenceSpecies.objects.values_list('data').filter(
                specie_id__in=species_ids)
            speciesList = ListFlowable([
                Paragraph(s[0][0]['vernacular_names'], styles['Left'])
                for s in species
            ],
                                       bulletFontName=BOLD_FONTNAME,
                                       bulletFontSize=MEDIUM_FONTSIZE)
            elements.append(speciesList)
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        try:
            # copy-to-licence sections with terms and additional information.
            activity_util = ActivitySchemaUtil(selected_activity.application)
            terms = selected_activity.additional_licence_info['terms']
            for term in terms:
                header = term['header']
                if not header:
                    continue
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                elements.append(Paragraph(header.upper(), styles['BoldLeft']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                text = activity_util.get_ctl_text(term)
                elements.append(Paragraph(text, styles['Left']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        except BaseException:
            pass

        # PurposeSpecies Section
#        for s in purpose.purpose_species_json:
#            if s.has_key('is_additional_info') and s['is_additional_info']:
#                continue
#
#            if s['details']:
#                parser = HtmlParser(s['details'])
#
#                # Get and Display Purpose Species Header
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(
#                    Paragraph(
#                        s['header'],
#                        styles['BoldLeft']
#                    )
#                )
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#
#                purposeSpeciesList = add_parsed_details(parser, list_flowable=False)
#                for info_item in purposeSpeciesList:
#                    elements.append(KeepTogether(info_item))

        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info']:
                continue

            if s['details']:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesList:
                    elements.append(KeepTogether(info_item))

        # End PurposeSpecies Section

        # application conditions
        activity_conditions = selected_activity.application.conditions.filter(
            licence_activity_id=selected_activity.licence_activity_id,
            licence_purpose_id=issued_purpose.purpose.id)

        if activity_conditions.exists():
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('CONDITIONS', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            # Conditions Section
            #            conditionList = []
            #            for s in activity_conditions.order_by('order'):
            #                parser = HtmlParser(s.condition)
            #                conditionList += add_parsed_details(parser, list_flowable=False)
            #                #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            #            conditionList = ListFlowable(
            #                conditionList,
            #                bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE
            #            )
            #            elements.append(conditionList)

            listcounter = 0
            conditionList = []
            for s in activity_conditions.order_by('order'):
                #_conditionList, listcounter += html_to_rl(s.condition, styles)
                _conditionList, listcounter = html_to_rl(
                    s.condition_text, styles, listcounter)
                conditionList += _conditionList

            for info_item in conditionList:
                elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements += _layout_extracted_fields(licence.extracted_fields)
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # signature block
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        issue_officer = '{} {}'.format(selected_activity.updated_by.first_name,
                                       selected_activity.updated_by.last_name)
        elements.append(Paragraph('____________________', styles['Left']))
        elements.append(Paragraph(issue_officer, styles['Left']))
        elements.append(Paragraph('LICENSING OFFICER', styles['Left']))
        elements.append(Paragraph('WILDLIFE PROTECTION BRANCH',
                                  styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Delegate of CEO', styles['ItalicLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # additional information
        # 'is_additional_info' Section from Purposespecies
        #        for s in purpose.purpose_species_json:
        #            if s.has_key('is_additional_info') and s['is_additional_info'] and s['details']:
        #                parser = HtmlParser(s['details'])
        #
        #                # Get and Display Purpose Species Header
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #                elements.append(
        #                    Paragraph(
        #                        s['header'],
        #                        styles['BoldLeft']
        #                    )
        #                )
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #
        #                purposeSpeciesInfoList = add_parsed_details(parser, list_flowable=False)
        #                #elements.append(purposeSpeciesInfoList)
        #                for info_item in purposeSpeciesInfoList:
        #                    elements.append(KeepTogether(info_item))

        # additional information
        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info'] and s[
                    'details']:
                # Get and Display Purpose Species Header
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesInfoList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesInfoList:
                    elements.append(KeepTogether(info_item))
        # End PurposeSpecies Section

        if licence.has_additional_information_for(selected_activity):
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(
                Paragraph('ADDITIONAL INFORMATION', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            conditions = activity_conditions
            infos = []
            c_num = 0
            for c_id, condition in enumerate(conditions.order_by('order')):
                info = None
                if condition.standard_condition:
                    info = condition.standard_condition.additional_information
                    c_num = c_id + 1
                if info:
                    infos.append('{0} (related to condition no.{1})'.format(
                        info.encode('utf8'), c_num))

            # Conditions Section


#            for s in infos:
#                parser = HtmlParser(s)
#                infoList = add_parsed_details(parser)
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(infoList)

            for s in infos:
                infoList, listcounter = html_to_rl(s, styles)
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                #elements.append(infoList)
                for info_item in infoList:
                    elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements.append(PageBreak())

    # create the summary for this licence.
    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_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 Summary', styles['InfoTitleVeryLargeCenter']))
    # elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # elements.append(Paragraph('Activities', styles['BoldLeft']))
    # elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # activityList = ListFlowable(
    #     [Paragraph("{name}".format(
    #         name=selected_activity.licence_activity.name
    #     ),
    #         styles['Left'],
    #     ) for selected_activity in licence.current_activities],
    #     bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
    # elements.append(activityList)

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

    include = [
        ApplicationSelectedActivityPurpose.PURPOSE_STATUS_SUSPENDED,
        ApplicationSelectedActivityPurpose.PURPOSE_STATUS_CURRENT,
        ApplicationSelectedActivityPurpose.PURPOSE_STATUS_DEFAULT,
    ]

    licence_purposes = [
        p for p in licence.get_purposes_in_sequence()
        if p.purpose_status in include and p.is_issued and p.expiry_date
    ]

    purposeList = ListFlowable([
        Paragraph(
            "{name} {start} - {end} ({status})".format(
                name=p.purpose.name,
                status=p.purpose_status,
                start=p.start_date.strftime('%d/%m/%Y'),
                end=p.expiry_date.strftime('%d/%m/%Y'),
            ),
            styles['Left'],
        ) for p in licence_purposes
    ],
                               bulletFontName=BOLD_FONTNAME,
                               bulletFontSize=MEDIUM_FONTSIZE)
    elements.append(purposeList)

    elements.append(PageBreak())

    for purpose in licence_purposes:
        # if not purpose.is_issued or purpose.purpose_status not in include:
        #     # Exclude purposes that are not issued.
        #     continue
        _create_licence_purpose(elements, purpose.selected_activity, purpose)

    doc.build(elements)

    return licence_buffer
def _create_invoice(invoice_buffer, proposal):

    global DPAW_HEADER_LOGO
    #    if  cols_var["TEMPLATE_GROUP"] == 'rottnest':
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png')
    #    else:
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments','static', 'payments', 'img','dbca_logo.jpg')
    DPAW_HEADER_LOGO = os.path.join(settings.PROJECT_DIR, 'payments', 'static',
                                    'payments', 'img', 'dbca_logo.jpg')

    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

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

    # this is the only way to get data into the onPage callback function
    #doc.invoice = invoice
    doc.proposal = proposal
    #owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    #items = invoice.order.lines.all()
    #items = booking.as_line_items
    #discounts = invoice.order.basket_discounts
    #if invoice.text:
    #    elements.append(Paragraph(invoice.text, styles['Left']))
    #    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))

    data = [['Item', 'Product', 'Qty', 'Unit Price', 'Total']
            #['Item', 'Product', 'Status', 'Qty', 'Fees']
            ]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    #for val, item in enumerate(booking.as_line_items, 1):
    total_amount = 0.0
    filming_fee = proposal.filming_fees.order_by('-id').first()
    lines = filming_fee.lines_aggregated
    if len(lines) == 0:
        lines = filming_fee.lines

    for val, item in enumerate(lines, 1):
        amount = float(item['price_incl_tax']) * item['quantity']
        data.append([
            val,
            Paragraph(item['ledger_description'], s),
            item['quantity'],
            currency(item['price_incl_tax']),
            currency(amount),
        ])
        total_amount += amount
        val += 1
    data.append(['', 'Total', '', '', currency(total_amount)])

    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    #if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
    #    elements.append(Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

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

    # Remitttance Frame
    #    elements.append(FrameBreak())
    #    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN *1.1))
    #    elements.append(boundary)
    #    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #
    #    remittance = Remittance(HEADER_MARGIN,HEADER_MARGIN - 10,invoice)
    #    elements.append(remittance)
    doc.build(elements)

    return invoice_buffer
예제 #30
0
               doc.width,
               doc.height,
               id='normal')

# Two Columns
frame1 = Frame(doc.leftMargin,
               doc.bottomMargin,
               doc.width / 2 - 6,
               doc.height,
               id='col1')
frame2 = Frame(doc.leftMargin + doc.width / 2 + 6,
               doc.bottomMargin,
               doc.width / 2 - 6,
               doc.height,
               id='col2')

Elements.append(Paragraph("Frame one column, " * 500, styles['Normal']))
Elements.append(NextPageTemplate('TwoCol'))
Elements.append(PageBreak())
Elements.append(Paragraph("Frame two columns,  " * 500, styles['Normal']))
Elements.append(NextPageTemplate('OneCol'))
Elements.append(PageBreak())
Elements.append(Paragraph("Une colonne", styles['Normal']))
doc.addPageTemplates([
    PageTemplate(id='OneCol', frames=frameT, onPage=foot1),
    PageTemplate(id='TwoCol', frames=[frame1, frame2], onPage=foot2),
])
# start the construction of the pdf
doc.build(Elements)
# use external program xpdf to view the generated pdf
# os.system("foxitreader basedoc.pdf")