예제 #1
0
import os
from reportlab.lib.utils import ImageReader
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import datetime

logo = ImageReader("graph.png")
canvas = canvas.Canvas("form.pdf", pagesize=letter)
canvas.setLineWidth(.3)
now = datetime.datetime.now()
#left value is HORIZONTALLY
canvas.setFont('Helvetica', 40)
canvas.drawString(120, 750, 'Fish Capture Report')
canvas.setFont('Helvetica', 15)
canvas.drawString(20, 700, 'Ship Name')
canvas.drawString(20, 680, 'Longtitude')
canvas.drawString(20, 660, 'Latitude')
canvas.drawString(20, 640, now.strftime("%Y-%m-%d %H:%M:%S"))
canvas.drawImage(
    logo, 110, 300, width=450,
    height=300)  #first one is to move left right, second is up and down.
canvas.drawString(160, 250, 'Logistics : ')
canvas.drawString(230, 250, 'Logistics Info ')
canvas.drawString(160, 230, 'Logistics : ')
canvas.drawString(230, 230, 'Logistics Info ')
canvas.drawString(160, 210, 'Logistics : ')
canvas.drawString(230, 210, 'Logistics Info ')

canvas.setFont('Helvetica', 30)
canvas.drawString(110, 100, 'Final Decision: ')
#connect the decision here and display in the box below
    def __payment_line(self):
        canvas = self.canv
        current_y, current_x = self.current_y, self.current_x
        bpay_logo = ImageReader(BPAY_LOGO)
        #current_y -= 40
        # Pay By Cheque
        cheque_x = current_x + 4 * inch
        cheque_y = current_y - 30
        canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE)
        canvas.drawString(cheque_x, cheque_y, 'Pay By Cheque:')
        canvas.setFont(DEFAULT_FONTNAME, 9)
        cheque_y -= 15
        canvas.drawString(
            cheque_x, cheque_y,
            'Make cheque payable to: Department of Parks and Wildlife')
        cheque_y -= 15
        canvas.drawString(cheque_x, cheque_y,
                          'Mail to: Department of Parks and Wildlife')
        cheque_y -= 15
        canvas.drawString(cheque_x + 32, cheque_y, 'Locked Bag 30')
        cheque_y -= 15
        canvas.drawString(cheque_x + 32, cheque_y,
                          'Bentley Delivery Centre WA 6983')
        if settings.BPAY_ALLOWED:
            # Outer BPAY Box
            canvas.rect(current_x, current_y - 25, 2.3 * inch, -1.2 * inch)
            canvas.setFillColorCMYK(0.8829, 0.6126, 0.0000, 0.5647)
            # Move into bpay box
            current_y += 5
            box_pos = current_x + 0.1 * inch
            bpay_logo_size = bpay_logo.getSize()
            canvas.drawImage(bpay_logo,
                             box_pos,
                             current_y - (bpay_logo_size[1] / 12 * 1.7),
                             height=bpay_logo_size[1] / 12,
                             width=bpay_logo_size[0] / 12,
                             mask='auto')
            # Create biller information box
            biller_x = box_pos + bpay_logo_size[0] / 12 + 1
            canvas.rect(biller_x,
                        (current_y - (bpay_logo_size[1] / 12 * 1.7)) + 3,
                        1.65 * inch, (bpay_logo_size[1] / 12) - 5)
            # Bpay info
            canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE)
            info_y = ((current_y -
                       (bpay_logo_size[1] / 12 * 1.7)) + 3) + (0.35 * inch)
            canvas.drawString(
                biller_x + 5, info_y,
                'Biller Code: {}'.format(self.invoice.biller_code))
            canvas.drawString(biller_x + 5, info_y - 20,
                              'Ref: {}'.format(self.invoice.reference))
            # Bpay Info string
            canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
            canvas.drawString(box_pos, info_y - 0.55 * inch,
                              'Telephone & Internet Banking - BPAY')
            canvas.setFont(DEFAULT_FONTNAME, 6.5)
            canvas.drawString(
                box_pos, info_y - 0.65 * inch,
                'Contact your bank or financial institution to make')
            canvas.drawString(
                box_pos, info_y - 0.75 * inch,
                'this payment from your cheque, savings, debit or')
            canvas.drawString(
                box_pos, info_y - 0.85 * inch,
                'transaction account. More info: www.bpay.com.au')

        self.current_y = current_y
예제 #3
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jan  7 16:57:12 2016

@author: aidanrocke
"""

from PIL import Image
import matplotlib.pyplot as plt
from io import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm

from reportlab.lib.utils import ImageReader

fig = plt.figure(figsize=(4, 3))
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')

imgdata = StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)  # rewind the data

Img = ImageReader(imgdata)

c = canvas.Canvas('test.pdf')
c.drawImage(Img, cm, cm, inch, inch)
c.save()
예제 #4
0
def _create_licence_header(canvas, doc, draw_page_number=True):
    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y = PAGE_HEIGHT - HEADER_MARGIN

    canvas.drawCentredString(
        PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE,
        'DEPARTMENT OF BIODIVERSITY, CONSERVATION AND ATTRACTIONS')

    current_y -= 30

    dpaw_header_logo = ImageReader(BW_DPAW_HEADER_LOGO)
    canvas.drawImage(dpaw_header_logo,
                     HEADER_MARGIN,
                     current_y - 40,
                     width=LICENCE_HEADER_IMAGE_WIDTH,
                     height=LICENCE_HEADER_IMAGE_HEIGHT)

    current_x = HEADER_MARGIN + LICENCE_HEADER_IMAGE_WIDTH + 5

    canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE)

    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      'Enquiries:')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      'Telephone:')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
                      'Facsimile:')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4,
                      'Web Site:')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
                      'Correspondance:')

    current_x += 80

    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      '17 DICK PERRY AVE, KENSINGTON, WESTERN AUSTRALIA')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      '08 9219 9000')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
                      '08 9219 8242')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4,
                      doc.site_url)

    canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
                      'Locked Bag 30')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
                      'Bentley Delivery Centre WA 6983')

    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y -= 36
    current_x += 200

    if draw_page_number:
        canvas.drawString(current_x,
                          current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER),
                          'PAGE')

    if hasattr(
            doc, 'licence'
    ) and doc.licence.licence_number is not None and doc.licence.licence_sequence:
        canvas.drawString(
            current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
            'NO.')

    canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE)

    current_x += 50

    if draw_page_number:
        canvas.drawString(current_x,
                          current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER),
                          str(canvas.getPageNumber()))

    if hasattr(
            doc, 'licence'
    ) and doc.licence.licence_number is not None and doc.licence.licence_sequence:
        canvas.drawString(
            current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
            '%s-%d' %
            (doc.licence.licence_number, doc.licence.licence_sequence))
예제 #5
0
 def draw(self):
     self.canv.drawImage(ImageReader(self.image), 0, 0, self.width, self.height)
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_template_1 = PageTemplate(id='Page1', frames=[page_frame_1, ], )
    doc = BaseDocTemplate(invoice_buffer, pageTemplates=[page_template_1, ], pagesize=A4,)  # showBoundary=Color(1, 0, 0))

    # Common
    FONT_SIZE_L = 11
    FONT_SIZE_M = 10
    FONT_SIZE_S = 8

    styles = StyleSheet1()
    style_normal = 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(style_normal)
    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'),
        ('VALIGN', (1, 3), (1, 3), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('SPAN', (1, 1), (2, 1)),
        ('SPAN', (0, 2), (0, 3)),
        ('SPAN', (1, 4), (2, 4)),
        ('SPAN', (1, 5), (2, 5)),
        ('SPAN', (1, 6), (2, 6)),
        ('SPAN', (1, 7), (2, 7)),
        ('SPAN', (1, 8), (2, 8)),
    ])
    date_str = gap(10) + '/' + gap(10) + '/'
    col_width = [30*mm, 125*mm, 25*mm, ]

    data = []
    data.append([
        Paragraph('<strong>Western Australia</strong>', style_normal),
        Paragraph('<i>Biodiversity Conservation Act 2016</i><br /><strong>Obtaining Records and Directions</strong>', style_normal),
        Paragraph('<strong>No.</strong><br />' + get_font_str(str(sanction_outcome.lodgement_number)), style_normal),
    ])
    offender = sanction_outcome.get_offender()
    data.append([
        Paragraph('<strong>To</strong>', style_normal),
        [
            Paragraph('Given names: ' + get_font_str(offender[0].first_name), style_normal),
            Paragraph('Surname: ' + get_font_str(offender[0].last_name), style_normal),
            Spacer(0, 3*mm),
        ],
        '',
    ])
    fields = [offender[0].residential_address.line1, offender[0].residential_address.line2, offender[0].residential_address.line3] if offender[0].residential_address else []
    fields = [unicode_compatible(f).encode('utf-8').decode('unicode-escape').strip() for f in fields if f]
    no_and_street = ', '.join(fields)
    postcode = offender[0].residential_address.postcode if offender[0].residential_address else ''
    town_suburb = offender[0].residential_address.locality if offender[0].residential_address else ''
    data.append([
        Paragraph('<strong>Address</strong>', style_normal),
        [
            Paragraph('No and Street: <br />' + get_font_str(str(no_and_street)), style_normal),
            Paragraph('Town/Suburb: <br />' + get_font_str(town_suburb), style_normal),
        ],
        Paragraph('Post Code: <br />' + get_font_str(postcode), style_normal),
    ])
    offender_dob = offender[0].dob.strftime('%d/%m/%Y') if offender[0].dob else ''
    data.append(([
        '',
        Paragraph('Date of Birth: ' + get_font_str(offender_dob), style_normal),
        [
            Paragraph('Gender:', style_normal),
            Paragraph('M' + gap(3) + 'F' + gap(3) + 'U', style_normal),
        ],
    ]))
    data.append([
        Paragraph('<strong>Direction<br /><br />* Delete as appropriate.<br /><br /># Enter details of direction given.</strong>', style_normal),
        [Paragraph('Under the <strong><i>Biodiversity Conservation Act 2016 s204(2) (a), (b), (d)*</i></strong>, I direct you to - #<br />', style_normal),
         Spacer(0, 20*mm),
         Paragraph('Under the <strong><i>Biodiversity Conservation Act 2016 s205(2)</i></strong>, I direct you to - #', style_normal),
         Spacer(0, 20*mm),
         ],
        '',
    ])
    data.append([
        Paragraph('<strong>Warning</strong>', style_normal),
        Paragraph('<strong>If you do not obey this direction you may be liable to a fine of $10,000.00.</strong>', style_normal),
        '',
    ])
    region_district = ' / '.join(list(filter(None, [get_font_str(sanction_outcome.district), get_font_str(sanction_outcome.region)])))
    data.append([
        Paragraph('<strong>Issuing officer’s signature and details</strong>', style_normal),
        [
            Paragraph('I issue this direction on this date and at this time<br />'
                      'Date: ' + get_font_str(sanction_outcome.date_of_issue.strftime('%d/%m/%Y')) + '<br />'
                      'Time: ' + get_font_str(sanction_outcome.time_of_issue.strftime('%I:%M %p')), style_normal),
            Paragraph('Name and AO Number: ' + get_font_str(sanction_outcome.responsible_officer.get_full_name()), style_normal),
            Paragraph('Signature', style_normal),
            Paragraph('District/Region: ' + region_district, style_normal),
        ],
        '',
    ])
    # Paragraph('District/Region: ' + get_font_str(sanction_outcome.district) + ' / ' + get_font_str(sanction_outcome.region), style_normal),
    data.append([
        Paragraph('<strong>Witnessing officer</strong>', style_normal),
        [
            Paragraph('Name and AO Number:', style_normal),
            Paragraph('Signature: ', style_normal),
            Paragraph('District/Region:', style_normal),
        ],
        '',
    ])
    data.append([
        Paragraph('<strong>Recipient\'s signature [Optional]</strong>', style_normal),
        Paragraph('I acknowledge receiving this direction. I understand what it says', style_normal),
        ''
    ])
    t1 = Table(data, style=invoice_table_style, colWidths=col_width, )

    # Table 2
    col_width = [30*mm, 150*mm, ]
    col_width_internal = [15*mm, 130*mm, ]
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('TOPPADDING', (0, 0), (-1, -1), 2),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ('BACKGROUND', (0, 0), (1, 0), (0.8, 0.8, 0.8)),
        ('SPAN', (0, 0), (1, 0)),
        ('SPAN', (0, 1), (1, 1)),
        ('BACKGROUND', (0, 5), (1, 5), (0.8, 0.8, 0.8)),
        ('SPAN', (0, 5), (1, 5)),
        ('SPAN', (0, 6), (1, 6)),
    ])
    data = []
    data.append([
        Paragraph('<strong>Section 204 - Obtaining records:</strong>', styles['Centre']),
        '',
    ])
    data.append([
        Paragraph('For inspection purposes a wildlife officer may do one or more of the following -', styles['Centre']),
        '',
    ])
    tbl_style_internal = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
    ])
    data.append([
        Paragraph('s204(2)(a)', style_normal),
        Table([[
            Paragraph('a)', styles['Right']),
            Paragraph('direct a person who has the custody or control of a record to give the wildlife officer the record or a copy of it;', style_normal),
        ]], style=tbl_style_internal, colWidths=col_width_internal),
    ])
    data.append([
        Paragraph('s204(2)(b)', style_normal),
        Table([[
            Paragraph('b)', styles['Right']),
            Paragraph('direct a person who has the custody or control of a record, computer or thing to make or print out a copy of the record or to operate the computer or thing;', style_normal),
        ]], style=tbl_style_internal, colWidths=col_width_internal),
    ])
    data.append([
        Paragraph('s204(2)(d)', style_normal),
        Table([[
            Paragraph('d)', styles['Right']),
            Paragraph('direct a person who is or appears to be in control of a record that the wildlife officer reasonably suspects is a relevant record to give the wildlife officer a translation, code, password or other information necessary to gain access to or interpret and understand the record.', style_normal),
        ]], style=tbl_style_internal, colWidths=col_width_internal),
    ])
    data.append([
        Paragraph('<strong>Section 205 - Directions</strong>', styles['Centre']),
        '',
    ])
    data.append([
        Paragraph('A wildlife officer may do one or more of the following -', styles['Centre']),
        '',
    ])
    data.append([
        Paragraph('s205(2)(a)(i)<br />s205(2)(a)(ii)', style_normal),
        [ Paragraph('For inspection purposes direct an occupier of a place or vehicle, or a person who is or appears to be in possession or control of a thing, to give to the wildlife officer, orally or in writing -', style_normal),
            Table([
                [
                    Paragraph('(i)', styles['Right']),
                    Paragraph(
                        'any information in the person’s possession or control as to the name and address of the owner of the place, vehicle or thing; and',
                        style_normal),
                ],
                [
                    Paragraph('(ii)', styles['Right']),
                    Paragraph(
                        'any other information in the person’s possession or control that is relevant to an inspection',
                        style_normal),
                ],
            ], style=tbl_style_internal, colWidths=col_width_internal),
        ],
    ])
    data.append([
        Paragraph('s205(2)(b)', style_normal),
        Paragraph('For inspection purposes direct a person who is or appears to be in possession or control of an organism or potential carrier to give the wildlife officer any information in the person’s possession or control as to the name and address of any person from whom the organism or potential carrier or to whom a similar organism or potential carrier has been supplied;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(c)', style_normal),
        Paragraph('For inspection purposes direct an occupier of a place or vehicle to answer questions;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(d)', style_normal),
        Paragraph('For inspection purposes direct an occupier of a place or vehicle to produce a specified thing or a thing of a specified kind;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(e)', style_normal),
        Paragraph('For inspection purposes direct an occupier of a place or vehicle to open or unlock any thing in or on the place or vehicle to which the wildlife officer requires access;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(f)', style_normal),
        Paragraph('Direct an occupier of a place or vehicle to give the wildlife officer a plan, or access to a plan, of the place or vehicle;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(g)', style_normal),
        Paragraph('Direct an occupier of a place or vehicle, or a person who is or appears to be in possession or control of a thing, to give the wildlife officer any assistance that the wildlife officer reasonably needs to carry out the wildlife officer’s functions in relation to the place, vehicle or thing;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(h)', style_normal),
        Paragraph('Direct an occupier of a vehicle to move the vehicle to a specified place for inspection or treatment;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(i)', style_normal),
        Paragraph('direct a person who is or could be carrying an organism or potential carrier to go to a specified place for inspection or treatment;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(j)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of a consignment of goods or a potential carrier to move the consignment or potential carrier to a specified place for inspection or treatment;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(k)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of an organism to do anything necessary to identify the organism;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(l)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of an animal to restrain, muster, round up, yard, draft or otherwise move or handle the animal or to remove the animal to a specified place for inspection or treatment;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(m)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of any goods, vehicle, package or container to label it;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(n)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of an organism, potential carrier or other thing prohibited, controlled, regulated or managed under this Act to keep that organism, potential carrier or other thing in the possession of that person until further directed by the wildlife officer;', style_normal),
    ])
    data.append([
        Paragraph('s205(2)(o)', style_normal),
        Paragraph('Direct a person who is or appears to be in control of an organism, potential carrier or other thing prohibited, controlled, regulated or managed under this Act to leave that organism, potential carrier or other thing at a specified place until further directed by the wildlife officer.', style_normal),
    ])
    t2 = Table(data, style=invoice_table_style, colWidths=col_width, )


    # Append tables to the elements to build
    elements = []
    elements.append(dbca_logo)
    elements.append(Spacer(0, 5*mm))
    elements.append(t1)
    elements.append(PageBreak())
    elements.append(Spacer(0, 10*mm))
    elements.append(t2)

    doc.build(elements)
    return invoice_buffer
def render_label(request, c, metrics, da, badge_img, debug):
    """Render a single label"""
    badge = da.badge

    badge_image_width = (1.0 + (1.0 / 64.0)) * inch
    badge_image_height = (1.0 + (1.0 / 64.0)) * inch

    qr_left = badge_image_width - metrics['qr_overlap']
    qr_bottom = badge_image_height - metrics['qr_overlap']
    qr_width = metrics['width'] - qr_left
    qr_height = metrics['height'] - qr_bottom

    if False and debug:
        # Draw some layout lines on debug.
        c.setLineWidth(0.3)
        c.rect(0, 0, metrics['width'], metrics['height'])
        c.rect(qr_left, qr_bottom, qr_width, qr_height)
        c.rect(0, 0, badge_image_width, badge_image_height)

    fit_text(c, da.badge.title, 0.0, badge_image_height, badge_image_width,
             qr_height)

    c.saveState()
    c.rotate(-90)

    code_height = qr_height * (0.45)
    claim_height = qr_height - code_height

    c.setFont("Courier", code_height)
    c.drawCentredString(0 - (badge_image_width / 2.0),
                        metrics['height'] - code_height, da.claim_code)

    text = """
        <font name="Helvetica">Claim at</font> <font name="Courier">%s</font>
    """ % (settings.SITE_TITLE)
    fit_text(c, text, 0 - badge_image_height, badge_image_width,
             badge_image_width, claim_height)

    c.restoreState()

    # Attempt to build a QR code image for the claim URL
    claim_url = request.build_absolute_uri(da.get_claim_url())
    qr_img = None
    try:
        # Try using PyQRNative: http://code.google.com/p/pyqrnative/
        # badg.us should have this in vendor-local
        from PyQRNative import QRCode, QRErrorCorrectLevel
        # TODO: Good-enough settings?
        if len(claim_url) < 20:
            qr = QRCode(3, QRErrorCorrectLevel.L)
        elif len(claim_url) < 50:
            qr = QRCode(4, QRErrorCorrectLevel.L)
        else:
            qr = QRCode(10, QRErrorCorrectLevel.L)
        qr.addData(claim_url)
        qr.make()
        qr_img = ImageReader(qr.makeImage())

    except ImportError:
        try:
            # Hmm, if we don't have PyQRNative, then try abusing this web
            # service. Should be fine for low volumes.
            qr_url = ("http://api.qrserver.com/v1/create-qr-code/?%s" %
                      urllib.urlencode({
                          'size': '%sx%s' % (500, 500),
                          'data': claim_url
                      }))

            qr_img = ImageReader(StringIO(urllib2.urlopen(qr_url).read()))

        except Exception:
            # Ignore issues in drawing the QR code - maybe show an error?
            pass

    if qr_img:
        c.drawImage(qr_img, qr_left, qr_bottom, qr_width, qr_height)

    c.drawImage(badge_img, 0.0 * inch, 0.0 * inch, badge_image_width,
                badge_image_height)
예제 #8
0
def _create_approval_header(canvas, doc, draw_page_number=True):
    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y = PAGE_HEIGHT - HEADER_MARGIN

    #canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, '{}'.format(settings.DEP_NAME.upper()))

    current_y -= 30

    dpaw_header_logo = ImageReader(BW_DPAW_HEADER_LOGO)
    canvas.drawImage(dpaw_header_logo,
                     HEADER_MARGIN,
                     current_y - 58,
                     width=LICENCE_HEADER_IMAGE_WIDTH,
                     height=LICENCE_HEADER_IMAGE_HEIGHT)

    current_x = HEADER_MARGIN + LICENCE_HEADER_IMAGE_WIDTH + 5

    # canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE)

    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), 'Enquiries:')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Telephone:')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Facsimile:')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Web Site:')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Correspondance:')

    # current_x += 80

    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
    #                   '17 DICK PERRY AVE, KENSINGTON, WESTERN AUSTRALIA')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, '08 9219 9000')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, '08 9219 8242')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, doc.site_url)

    # canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Locked Bag 30')
    # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
    #                   'Bentley Delivery Centre WA 6983')

    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    #print current_x, current_y

    #current_y -= 36
    current_y -= 2
    current_x += 10

    if draw_page_number:
        canvas.drawString(current_x,
                          current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER),
                          'PAGE')

    if hasattr(doc, 'approval'):
        canvas.drawString(
            current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
            'NO.')

    canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE)

    current_x += 50

    if draw_page_number:
        canvas.drawString(current_x,
                          current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER),
                          str(canvas.getPageNumber()))

    if hasattr(doc, 'approval'):
        canvas.drawString(
            current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
            '{}'.format(doc.approval.lodgement_number))
예제 #9
0
 def raster_image(self, obj):
     self.pdf.saveState()
     apply(self.pdf.transform, obj.Trafo().coeff())
     img = obj.data.image.copy()
     self.pdf.drawImage(ImageReader(img), 0, 0, mask='auto')
     self.pdf.restoreState()
예제 #10
0
def fill_subscription_form(data, base_dir, user_id):
    """
    fill the subscription form (file 'empty_form.pdf') with user data.
    """
    empty_form = PdfFileReader(open('empty_form.pdf', 'rb'), strict=False)
    packet = StringIO.StringIO()
    can = canvas.Canvas(packet, A4)

    # fill it with user data
    # Yeah, the coordinates are hard-coded... FML

    # red header
    can.setFillColor('red')
    can.drawString(
        60, 670.0,
        u'{0} {1} / {2}'.format(data['profile']['last_name'],
                                data['profile']['first_name'], user_id))

    can.setFillColor('black')
    can.setFontSize(10)

    # last name
    can.drawString(60, 470.0, data['profile']['last_name'])
    # first name
    can.drawString(60, 440.7, data['profile']['first_name'])
    # birth date and birth place
    can.drawString(
        60, 411.4, '{0}, {1}'.format(data['profile']['birth_place'],
                                     data['profile']['birth_date']))
    # nationality
    can.drawString(60, 382.1, data['profile']['nationality'])
    # address
    _a = data['Home Address']
    address = u'{0}{1}, {2}, {3}, {4}, {5}'.format(
        _a['Street 1'],
        ', ' + _a['Street 2'] if _a['Street 2'] else '',
        _a['City'],
        _a['State/Province'],
        _a['Country'],
        _a['Postal code'],
    )
    can.drawString(60, 352.8, address)
    # phone
    can.drawString(60, 323.5, data['profile']['mobile_phone'])
    # mail
    can.drawString(60, 294.2, data['profile']['email'])
    # school name
    can.drawString(60, 174.5, data['School']['Name of the School'])
    # school's address
    can.drawString(60, 146, data['School']["School's Address"])
    # reference professor
    can.drawString(60, 116.5, data['School']['Reference Professor'])

    def guess_photo_path():
        """
        Try to guess the path of the profile photo of a student where when it is
        not specified in data.json.
        """
        extensions = ['jpg', 'png', 'tiff', 'gif', 'jpeg']
        for ext in extensions:
            path = join(base_dir, 'profile.{0}'.format(ext))
            if exists(path):
                return path
        return None  # wtf, dude

    # try to guess the path of the profile picture
    if 'photo' in data['profile']:
        photo_path = data['profile']['photo'].split('/')[-1]
    else:
        photo_path = guess_photo_path()

    if photo_path is not None:
        photo_path = join(base_dir, photo_path)
        photo = Image.open(photo_path)
        W, H = 137, 152

        # if the image is too large, then resize it to fill in the box
        if photo.size[0] > W or photo.size[1] > H:
            photo.thumbnail(map(int, (W, H)), Image.ANTIALIAS)

        # calculate the left and top margin to center the image in the box
        left, top = 354.5 + (W - photo.size[0]) / 2, \
            526.7 + (H - photo.size[1]) / 2

        # ...and draw it
        can.drawImage(ImageReader(photo), left, top, preserveAspectRatio=True)

    can.save()

    # move to the beginning of the StringIO buffer
    packet.seek(0)
    new_pdf = PdfFileReader(packet, strict=False)

    # generate the pdf
    page = empty_form.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    return page
예제 #11
0
 def drawImage(self, image):
     from reportlab.lib.utils import ImageReader
     im = ImageReader(image.path)
     self._canvas.drawImage(im._image, image.x, image.y, image.width,
                            image.height)
예제 #12
0
def getAsignacionesPDF(request,id_operario=None):
    operario=Operario.objects.get(Q(id=id_operario))
    asignaciones=AsignacionDet.objects.filter(operario_id=operario.id)
    asigAux={}
    listaAsignaciones=[]
    total=0
    diasLibres=diasLibres=getDiaLibre(id_operario)
    cantAsignaciones=0
    for a in asignaciones:
        cantAsignaciones+=1
        total=total+int(a.totalHoras)

    diaLibre1=diasLibres[0]["nombre"]
    hora=diasLibres[0]["hEntrada"].split(':')
    hora1=hora[0]+':'+hora[1]
    diaLibre2=diasLibres[len(diasLibres)-1]["nombre"]
    hora=diasLibres[len(diasLibres)-1]["hSalida"].split(':')
    hora2=hora[0]+':'+hora[1]


    
    response=HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+operario.nombre+' '+operario.apellido+' - '+operario.nroLegajo+'.pdf'
    buffer = BytesIO()
    c=canvas.Canvas(buffer,pagesize=A4)

    c.setFont('Helvetica-Bold',18)
    c.setFillColor(HexColor('#86273e'))
    c.drawString(30,750,'Reporte de Operario')
    c.setFont('Helvetica',12)
    c.drawString(50,700,'Nombre')
    c.drawString(200,700,'Apellido')
    c.drawString(350,700,'Legajo')
    c.drawString(50,650,'Dia Libre Inicio')
    c.drawString(200,650,'Hora')
    c.drawString(350,650,'Dia Libre Fin')
    c.drawString(470,650,'Hora')
    c.setFillColor(HexColor('#000000'))
    c.drawString(50,680,operario.nombre)
    c.drawString(200,680,operario.apellido)
    c.drawString(350,680,operario.nroLegajo)
    c.drawString(50,630,diaLibre1)
    c.drawString(200,630,hora1)
    c.drawString(350,630,diaLibre2)
    c.drawString(470,630,hora2)
    c.setFont('Helvetica-Bold',14)
    c.setFillColor(HexColor('#86273e'))
    c.drawString(30,580,'Total Horas Asignadas:')
    c.setFillColor(HexColor('#000000'))
    totalAux=str(total)+" hrs."
    c.drawString(200,580,totalAux) 
    png = r'.\static\logo1.png'
    logo=ImageReader(png)
    c.drawImage(logo,480,770,width=90,height=60,mask='auto')
    c.line(30,720,580,720)
    c.line(30,720,30,620)    
    c.line(30,620,580,620)
    c.line(580,720,580,620)   

    date=datetime.today().strftime('%d/%m/%Y')
    c.setFont('Helvetica',14)
    c.drawString(490,750,date)

    page=c.getPageNumber()
    text="%s" %page
    c.drawRightString(100*mm,20*mm,text)

    width,height=A4

    styles=getSampleStyleSheet()
    styleBH=styles["Normal"]
    styleBH.alignment=TA_CENTER
    styleBH.fontSize=10
    styleBH.textColor=HexColor('#86273e')  

    nro=Paragraph('''Nro''',styleBH)
    pSer=Paragraph('''Punto Servicio''',styleBH)
    totalHrs=Paragraph('''Total Horas''',styleBH)
    lns=Paragraph('''Lunes''',styleBH)
    mrts=Paragraph('''Martes''',styleBH)
    mrcls=Paragraph('''Miércoles''',styleBH)
    jvs=Paragraph('''Jueves''',styleBH)
    vrns=Paragraph('''Viernes''',styleBH)
    sbd=Paragraph('''Sábado''',styleBH)
    dmg=Paragraph('''Domingo''',styleBH)

    data=[]
    encabezados=[nro,pSer,totalHrs,lns,mrts,mrcls,jvs,vrns,sbd,dmg]
    data.append(encabezados)

    

    styleN=styles["BodyText"]
    styleN.alignment=TA_CENTER
    styleN.fontSize=8

    i=1
    l=[]
    high=510
    
    for a in asignaciones:
        listaAsigs=[]
        cab=AsignacionCab.objects.get(id=a.asignacionCab_id)
        puntoServ=cab.puntoServicio.NombrePServicio
        if(a.lunEnt and a.lunSal):
            h1=str(a.lunEnt).split(':')
            h2=str(a.lunSal).split(':')
            lunes=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            lunes=Paragraph(lunes,styleN)
        else:
            lunes=""
        if(a.marEnt and a.marSal):
            h1=str(a.marEnt).split(':')
            h2=str(a.marSal).split(':')
            martes=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            martes=Paragraph(martes,styleN)
        else:
            martes=""
        if(a.mieEnt and a.mieSal):
            h1=str(a.mieEnt).split(':')
            h2=str(a.mieSal).split(':')
            miercoles=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            miercoles=Paragraph(miercoles,styleN)
        else:
            miercoles=""
        if(a.jueEnt and a.jueSal):
            h1=str(a.jueEnt).split(':')
            h2=str(a.jueSal).split(':')
            jueves=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            jueves=Paragraph(jueves,styleN)
        else:
            jueves=""
        if(a.vieEnt and a.vieSal):
            h1=str(a.vieEnt).split(':')
            h2=str(a.vieSal).split(':')
            viernes=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            viernes=Paragraph(viernes,styleN)
        else:
            viernes=""
        if(a.sabEnt and a.sabSal):
            h1=str(a.sabEnt).split(':')
            h2=str(a.sabSal).split(':')
            sabado=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            sabado=Paragraph(sabado,styleN)
        else:
            sabado=""
        if(a.domEnt and a.domSal):
            h1=str(a.domEnt).split(':')
            h2=str(a.domSal).split(':')
            domingo=h1[0]+':'+h1[1]+" a "+h2[0]+':'+h2[1]
            domingo=Paragraph(domingo,styleN)
        else:
            domingo=""
        nro=Paragraph('''Nro''',styleBH)
        puntoServ=Paragraph(puntoServ,styleN)
        totalHrs=Paragraph(a.totalHoras,styleN)
        listaAsigs=[i,puntoServ,totalHrs,lunes,martes,miercoles,jueves,viernes,sabado,domingo]
        data.append(listaAsigs)
        i+=1
        high-=18

    table=Table(data,colWidths=[1 * cm, 2.5 * cm, 2 * cm, 2 * cm, 2 * cm, 2 * cm, 2 * cm, 2 * cm, 2 * cm, 2 * cm])
    table.setStyle(TableStyle([
        ('BOX',(0,0),(-1,-1),0.25,colors.black),
        ('GRID',(0,0),(-1,-1),0.3*mm,(0,0,0)),
    ]))

    if(total>0):
        table.wrapOn(c,width,height)
        table.drawOn(c,30,high)

        c.showPage()


    c.save()
    pdf=buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
예제 #13
0
    def draw_footer(self):
        if not self.receipt and self.paymentterms:
            fullheight = len(self.paymentterms.splitlines()) * self.fontheight(
                'DejaVu Serif', 6)
            t = self.canvas.beginText()
            t.setTextOrigin(cm(2), cm(1) + fullheight)
            t.setFont("DejaVu Serif", 6)
            self.textlines(t, self.paymentterms)
            self.canvas.drawText(t)

        if self.bankinfo:
            fullheight = 2 * self.fontheight('DejaVu Serif Bold', 9) + (
                2 + len(self.bankinfo.splitlines())) * self.fontheight(
                    'DejaVu Serif', 7)

            t = self.canvas.beginText()
            t.setTextOrigin(cm(13), cm(1) + fullheight)
            t.setFont("DejaVu Serif Bold", 9)
            t.textLine("Payment reference")

            t.setFont("DejaVu Serif", 7)
            t.textLine(self.paymentref)
            t.textLine("")

            t.setFont("DejaVu Serif Bold", 9)
            t.textLine("Bank references")

            t.setFont("DejaVu Serif", 7)
            self.textlines(t, self.bankinfo)

            self.canvas.drawText(t)

        if self.paymentlink:
            style = ParagraphStyle('temp')
            style.fontName = 'DejaVu Serif'
            style.fontSize = 5
            p = Paragraph(
                'Payment details and instructions:<br/><nobr><a href="{0}">{0}</a></nobr>'
                .format(self.paymentlink), style)
            p.wrapOn(self.canvas, cm(12), cm(2))
            p.drawOn(self.canvas, cm(2), cm(3.5))

            try:
                import qrencode
                (ver, size, qrimage) = qrencode.encode(self.paymentlink)
                qrimage = qrimage.resize((size * 4, size * 4))
                self.canvas.drawImage(ImageReader(qrimage), cm(2), cm(1.8),
                                      cm(1.5), cm(1.5))
            except ImportError:
                # If we don't have the qrcode module, we just don't bother drawing the
                # QR code for the link
                pass

            if self.reverse_vat:
                t = self.canvas.beginText()
                t.setTextOrigin(cm(2), cm(4.8))
                t.setFont("DejaVu Serif", 6)
                self.textlines(
                    t,
                    "* Services subject to the reverse charge - VAT to be accounted for by the recipient as per Article 196 of Council Directive 2006/112/EC"
                )
                self.canvas.drawText(t)
예제 #14
0
def add_page_data(canvas, page):

    # create dictionary containing names, styles and text data for text boxes to be drawn on page
    paragraphs = {
        config.id: PdfParagraph(canvas, text=getattr(page, config.id), **config.__dict__)
        for config in textarea_configs}

    # add static text boxes (not pulled from page object) to dictionary
    paragraphs.update({
        config.id: PdfParagraph(canvas, text=config.default_text, **config.__dict__)
        for config in (subcontractor1_config, subcontractor2_config)})

    # get necessary height for each text box
    heights = {id: paragraph.height for id, paragraph in paragraphs.items()}

    # draw border
    canvas.setStrokeColorRGB(0, 0, 0)
    canvas.setFillColorRGB(1, 1, 1)
    canvas.rect(x_margin, y_margin, border_width, border_height)

    # add text boxes for image description and title
    h1 = max(heights['desc1'], heights['desc2'])
    paragraphs['title'].paste(y=h1)
    paragraphs['desc1'].paste(height=h1)
    paragraphs['desc2'].paste(height=h1)

    # add text boxes for central column (date and scale)
    h2 = heights['date']
    paragraphs['scale'].paste(y=h2)
    paragraphs['date'].paste()

    # add text boxes for rightmost column (owner, contractor, subcontractor)

    # bottom row
    h3 = max(heights['owner1'], heights['owner2'])
    paragraphs['owner1'].paste(height=h3)
    paragraphs['owner2'].paste(height=h3)

    # middle row
    h4 = max(heights['subcontractor1'], heights['subcontractor2'])
    paragraphs['subcontractor1'].paste(y=h3, height=h4)
    paragraphs['subcontractor2'].paste(y=h3, height=h4)

    # position and insert logo image
    logo_y = logo_y_offset + h3 + y_margin
    img_io = BytesIO()
    logo_img.save(img_io, 'PNG', quality=70)
    img_io.seek(0)
    img_reader = ImageReader(img_io)
    canvas.drawImage(img_reader, logo_x, logo_y, logo_w, logo_h)

    # top row
    h5 = max(heights['contractor1'], heights['contractor2'])
    paragraphs['contractor1'].paste(y=h3 + h4, height=h5)
    paragraphs['contractor2'].paste(y=h3 + h4, height=h5)

    # available height space for placing image
    available_space = border_height - max(
        h1 + heights['title'],
        h2 + heights['scale'],
        h3 + h4 + h5)

    # save data on current page and open next page for editing
    canvas.showPage()

    # return available height space for use in positioning image
    return available_space
예제 #15
0
else:
    print("Size %s not valid" % args.size, end='')
    sys.exit(1)

# create label
c = canvas.Canvas(args.output, pagesize=LABEL_SIZE)

# transform so that we can render as if it's landscape mode
c.rotate(-90)
c.translate(-LABEL_SIZE[1], 0)

# draw qr code
qr_size = LABEL_SIZE[0]
if args.qr != None:
    qr = qrcode.make(args.qr)
    c.drawImage(ImageReader(qr._img), LABEL_SIZE[1] - qr_size, 0, qr_size,
                qr_size)
else:
    qr_size = 0

# draw bounding box
if args.bbox:
    c.rect(0, 0, LABEL_SIZE[1], LABEL_SIZE[0], stroke=1, fill=0)

# font
c.setFont(args.font, args.font_size)


# font metrics
def getTextHeight(fontName, fontSize):
    face = pdfmetrics.getFont(fontName).face
예제 #16
0
    def print_k_to_pdf(c, stk_code, date):
        """
        将一只股票的走势图打印到pdf中的一页
        :param c:
        :param stk_code:
        :param date:
        :return:
        """
        """ --------------------------------- 打印小时线图片 ------------------------------------ """
        c.setFont("song", 10)
        c.drawString(20, letter[1] - 20,
                     stk_code + ' ' + code2name(stk_code) + ' ' + '小时走势图')
        c.setLineWidth(0.5)
        c.line(10, h - 24, w - 10, h - 24)

        # 插入小时macd图
        try:
            image_file = PIL.Image.open(sea_select_pic_dir + date + '/' +
                                        'h_' + stk_code + '.png')
            c.drawImage(ImageReader(image_file),
                        x=w * 0.05,
                        y=h * 0.65,
                        height=0.3 * h,
                        width=0.45 * w,
                        preserveAspectRatio=True)
        except Exception as e:
            print('函数print_k_to_pdf:出错!\n' + str(e))

        # 插入小时指标图
        try:
            image_file = PIL.Image.open(sea_select_pic_dir + date + '/' +
                                        'h_idx_' + stk_code + '.png')
            c.drawImage(ImageReader(image_file),
                        x=w * 0.5,
                        y=h * 0.65,
                        height=0.3 * h,
                        width=0.45 * w,
                        preserveAspectRatio=True)
        except Exception as e:
            print('函数print_k_to_pdf:出错!\n' + str(e))
        """ --------------------------------- 打印日线图片 ------------------------------------ """
        c.setFont("song", 10)
        c.drawString(20, h * 0.65,
                     stk_code + ' ' + code2name(stk_code) + ' ' + '日线走势图')
        c.setLineWidth(0.5)
        c.line(10, h * 0.65 - 4, w - 10, h * 0.65 - 4)

        # 插入日线macd图
        try:
            image_file = PIL.Image.open(sea_select_pic_dir + date + '/' +
                                        'd_' + stk_code + '.png')
            c.drawImage(ImageReader(image_file),
                        x=w * 0.05,
                        y=h * 0.35,
                        height=0.3 * h,
                        width=0.45 * w,
                        preserveAspectRatio=True)
        except Exception as e:
            print('函数print_k_to_pdf:出错!\n' + str(e))

        # 插入日线指标图
        try:
            image_file = PIL.Image.open(sea_select_pic_dir + date + '/' +
                                        'd_idx_' + stk_code + '.png')
            c.drawImage(ImageReader(image_file),
                        x=w * 0.5,
                        y=h * 0.35,
                        height=0.3 * h,
                        width=0.45 * w,
                        preserveAspectRatio=True)
        except Exception as e:
            print('函数print_k_to_pdf:出错!\n' + str(e))
        """ --------------------------------- 打印周月线图片 ------------------------------------ """

        c.setFont("song", 10)
        c.drawString(20, h * 0.35,
                     stk_code + ' ' + code2name(stk_code) + ' ' + '周/月走势图')
        c.setLineWidth(0.5)
        c.line(10, h * 0.35 - 4, w - 10, h * 0.35 - 4)

        # 插入周线图
        try:
            image_file = PIL.Image.open(sea_select_pic_dir + date + '/' +
                                        'wm_' + stk_code + '.png')
            c.drawImage(ImageReader(image_file),
                        x=w * 0.05,
                        y=h * 0.05,
                        height=0.3 * h,
                        width=0.45 * w,
                        preserveAspectRatio=True)
        except Exception as e:
            print('函数print_k_to_pdf:出错!\n' + str(e))

        c.showPage()

        return c
예제 #17
0
def createPdf(reason):

    # Create Canva
    c = canvas.Canvas("mask_info.pdf")

    # Write customer info on pdf
    c.drawString(130, 625, context.user_data['name'])
    c.drawString(130, 595, context.user_data['birthdate'])
    c.drawString(130, 560, context.user_data['street'])
    c.drawString(130, 545, context.user_data['postalCode'])
    c.drawString(130, 530, context.user_data['city'])
    c.drawString(373, 142, context.user_data['city'])

    # Get Day & month
    today = datetime.datetime.now()

    # Write Day & month on Pdf
    c.drawString(475, 142, today.strftime("%d"))
    c.drawString(500, 142, today.strftime("%m"))

    # Get checkMarkLogo
    check_mark_logo = ImageReader(
        'https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Check_mark_9x9.svg/24px-Check_mark_9x9.svg.png'
    )

    # Write check mark on Pdf file
    if reason == "👩‍💻 Pro":
        c.drawImage(check_mark_logo, 45, 423, mask='auto')
    elif reason == "🍗 Achats de première nécessité":
        c.drawImage(check_mark_logo, 45, 348, mask='auto')
    elif reason == "💊 Santé":
        c.drawImage(check_mark_logo, 45, 271, mask='auto')
    elif reason == "👨‍👩‍👧‍👦 Famille":
        c.drawImage(check_mark_logo, 45, 303, mask='auto')
    else:
        c.drawImage(check_mark_logos, 45, 225, mask='auto')

    # Write check mark on Pdf file
    signature = ImageReader('signature_scaled_opt.png')
    c.drawImage(signature, 400, 0, mask='auto')

    # Save maskInfo pdf file
    c.save()

    # Merge two pdf
    certifFile = open('Ressources/certificate_of_travel_exemption.pdf', 'rb')
    pdfReader = PyPDF2.PdfFileReader(certifFile)
    certifFileFirstPage = pdfReader.getPage(0)
    maskInfoReader = PyPDF2.PdfFileReader(open('mask_info.pdf', 'rb'))
    certifFileFirstPage.mergePage(maskInfoReader.getPage(0))
    pdfWriter = PyPDF2.PdfFileWriter()
    pdfWriter.addPage(certifFileFirstPage)
    for pageNum in range(1, pdfReader.numPages):
        pageObj = pdfReader.getPage(pageNum)
        pdfWriter.addPage(pageObj)
    resultPdfFile = open('Attestation_Deplacement.pdf', 'wb')

    # Save merged Pdf file
    pdfWriter.write(resultPdfFile)
    certifFileFirstPage.close()
    resultPdfFile.close()
예제 #18
0
def dockets_pdf(request, slug):
    docket = get_object_or_404_perms(Docket, request.user, slug=slug)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="docket.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)

    # Operator Signature
    data = docket.operator_sign
    op_img = PIL.Image.open(BytesIO(base64.b64decode(data.split(',')[1])))
    op_sig = ImageReader(op_img)
    p.drawImage(op_sig,
                50,
                80,
                width=150,
                height=75,
                mask='auto',
                preserveAspectRatio=True,
                anchor='c')

    # Supervisor Signature
    data = docket.supervisor_sign
    sup_img = PIL.Image.open(BytesIO(base64.b64decode(data.split(',')[1])))
    sup_sig = ImageReader(sup_img)
    p.drawImage(sup_sig,
                350,
                80,
                width=150,
                height=75,
                mask='auto',
                preserveAspectRatio=True,
                anchor='c')

    logo = ImageReader("sniffersapp/static/images/logo.png")
    p.drawImage(logo,
                45,
                745,
                width=150,
                height=75,
                mask=None,
                preserveAspectRatio=True,
                anchor='c')

    p.setFillColorRGB(0.329, 0.329, 0.329)
    p.setFont('Helvetica-Bold', 16)
    #Docket Number
    p.drawString(400, 770, 'DOCKET: ')
    p.drawString(480, 770, "D-3-1000")

    p.setStrokeColorRGB(0.658, 0.658, 0.658)
    p.setLineWidth(1)
    p.line(40, 750, 554, 750)  # Page width 595

    # Customer
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 720, 'docket.operator_sign:')
    p.setFont('Helvetica', 10)
    p.drawString(120, 720, "Oneworksite")

    # Date
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 695, 'DATE: ')
    p.setFont('Helvetica', 10)
    p.drawString(90, 695, "June 14, 2018")
    # Day
    p.setFont('Helvetica-Bold', 10)
    p.drawString(225, 695, 'DAY: ')
    p.setFont('Helvetica', 10)
    p.drawString(260, 695, "Thursday")
    # Shift
    p.setFont('Helvetica-Bold', 10)
    p.drawString(380, 695, 'SHIFT: ')
    p.setFont('Helvetica', 10)
    p.drawString(430, 695, "Day")

    # Equipment
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 670, 'ITEM OR PLANT: ')
    p.setFont('Helvetica', 10)
    p.drawString(140, 670, "20T Excavator")
    # Unit Number
    p.setFont('Helvetica-Bold', 10)
    p.drawString(280, 670, 'UNIT NO: ')
    p.setFont('Helvetica', 10)
    p.drawString(335, 670, "EX120")

    # Operator
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 645, 'OPERATOR: ')
    p.setFont('Helvetica', 10)
    p.drawString(120, 645, "James O'Kane")
    # Supervisor
    p.setFont('Helvetica-Bold', 10)
    p.drawString(280, 645, 'SUPERVISOR: ')
    p.setFont('Helvetica', 10)
    p.drawString(365, 645, "Michael Smith")

    # Start time
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 620, 'START TIME: ')
    p.setFont('Helvetica', 10)
    p.drawString(120, 620, "05:30")
    # Finish time
    p.setFont('Helvetica-Bold', 10)
    p.drawString(225, 620, 'FINISH TIME: ')
    p.setFont('Helvetica', 10)
    p.drawString(295, 620, "18:00")
    # Total hours
    p.setFont('Helvetica-Bold', 10)
    p.drawString(380, 620, 'TOTAL HOURS: ')
    p.setFont('Helvetica', 10)
    p.drawString(475, 620, "10h 30m")

    # Lunch
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 595, 'LUNCH: ')
    p.setFont('Helvetica', 10)
    p.drawString(100, 595, "30mins")
    # Smoko
    p.setFont('Helvetica-Bold', 10)
    p.drawString(225, 595, 'SMOKO: ')
    p.setFont('Helvetica', 10)
    p.drawString(275, 595, "30mins")
    # Payable hours
    p.setFont('Helvetica-Bold', 10)
    p.drawString(380, 595, 'PAYABLE HOURS: ')
    p.setFont('Helvetica', 10)
    p.drawString(490, 595, "10h 30m")

    # Attachments
    p.setFont('Helvetica-Bold', 10)
    p.drawString(50, 570, 'ATTACHMENTS USED: ')
    p.setFont('Helvetica', 10)
    p.drawString(175, 570, "Rock breaker")

    # Prestart
    p.setStrokeColorRGB(0.329, 0.329, 0.329)
    p.setFont('Helvetica-Bold', 11)
    p.drawString(40, 520, 'PLANT OPERATORS DAILY SAFETY CHECKLIST')
    p.setFont('Helvetica-Bold', 9)
    #Item 1
    p.drawString(50, 495,
                 '1. Brakes, steering, gauges, lights, warning devices')
    #check box
    p.rect(515, 495, 10, 10, fill=0, stroke=1)
    p.line(515, 495, 525, 505)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 495, 515, 505)
    p.drawString(278, 492, '.' * 93)
    #Item 2
    p.drawString(
        50, 470,
        '2. Visibility - windscreen, wipers, washers, demisters, mirrors, windows'
    )
    p.rect(515, 470, 10, 10, fill=0, stroke=1)
    p.line(515, 470, 525, 480)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 470, 515, 480)
    p.drawString(365, 467, '.' * 58)
    #Item 3
    p.drawString(
        50, 445,
        '3. Cabin - access, seating, seatbelts, loose objects, control levers')
    p.rect(515, 445, 10, 10, fill=0, stroke=1)
    p.line(515, 445, 525, 455)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 445, 515, 455)
    p.drawString(340, 442, '.' * 68)
    #Item 4
    p.drawString(50, 420, '4. Wheels, tyres, nutes, damage, wear, pressure')
    p.rect(515, 420, 10, 10, fill=0, stroke=1)
    p.line(515, 420, 525, 430)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 420, 515, 430)
    p.drawString(263, 417, '.' * 99)
    #Item 5
    p.drawString(50, 395,
                 '5. Guards - in place, secure, warning signs lights, alarms')
    p.rect(515, 395, 10, 10, fill=0, stroke=1)
    p.line(515, 395, 525, 405)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 395, 515, 405)
    p.drawString(302, 392, '.' * 83)
    #Item 6
    p.drawString(50, 370, '6. Hydraulics - rams, hoses, leaks, wear')
    p.rect(515, 370, 10, 10, fill=0, stroke=1)
    p.line(515, 370, 525, 380)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 370, 515, 380)
    p.drawString(227, 367, '.' * 113)
    #Item 7
    p.drawString(
        50, 345,
        '7. Excessive wear - hooks, chains, pins, pivots, tracks, G.E.T')
    p.rect(515, 345, 10, 10, fill=0, stroke=1)
    p.line(515, 345, 525, 355)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 345, 515, 355)
    p.drawString(317, 342, '.' * 77)
    #Item 8
    p.drawString(50, 320, '8. Oils and coolants level')
    p.rect(515, 320, 10, 10, fill=0, stroke=1)
    p.line(515, 320, 525, 330)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 320, 515, 330)
    p.drawString(167, 317, '.' * 137)
    #Item 9
    p.drawString(50, 295,
                 '9. Misc, electrical, fire extinguisher, communications')
    p.rect(515, 295, 10, 10, fill=0, stroke=1)
    p.line(515, 295, 525, 305)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 295, 515, 305)
    p.drawString(285, 292, '.' * 90)
    #Item 10
    p.drawString(50, 270, '10. Quick hitch attachments')
    p.rect(515, 270, 10, 10, fill=0, stroke=1)
    p.line(515, 270, 525, 280)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 270, 515, 280)
    p.drawString(177, 267, '.' * 133)
    #Item 11
    p.drawString(50, 245,
                 '11. You are free from the influences of drugs and alcohol')
    p.rect(515, 245, 10, 10, fill=0, stroke=1)
    p.line(515, 245, 525, 255)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 245, 515, 255)
    p.drawString(302, 242, '.' * 83)
    #Item 12
    p.drawString(
        50, 220, '12. You are physically and mentally fit to operate or drive')
    p.rect(515, 220, 10, 10, fill=0, stroke=1)
    p.line(515, 220, 525, 230)  #(X-start, Y-start, X-finish, Y-finish )
    p.line(525, 220, 515, 230)
    p.drawString(302, 220, '.' * 83)
    # Faults
    p.setFont('Helvetica-Bold', 9)
    p.drawString(50, 195, 'Details of Fault/Defect: ')
    p.setFont('Helvetica', 9)
    p.drawString(160, 195, "Broken windscreen")
    # Reported to
    p.setFont('Helvetica-Bold', 9)
    p.drawString(50, 170, 'Fault Reported to: ')
    p.setFont('Helvetica', 9)
    p.drawString(140, 170, "Adam Morris")

    # Close the PDF object cleanly.
    p.showPage()
    p.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
예제 #19
0
 def __init__(self, filename, caption, background=None):
     assert os.path.isfile(filename), 'image file %s not found' % filename
     from reportlab.lib.utils import ImageReader
     w, h = ImageReader(filename).getSize()
     self.filename = filename
     FlexFigure.__init__(self, w, h, caption, background)
예제 #20
0
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib import pagesizes
from reportlab.platypus import Paragraph, Frame, KeepInFrame
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib.enums import TA_CENTER

logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')

canvas = Canvas('output.pdf', pagesize=pagesizes.A4)
(width, height) = pagesizes.A4

background_img = 'background.png'
canvas.drawImage(background_img, 0, 0, width=width, height=height, mask='auto')

canvas.drawImage(logo, width / 4.0, 550, width=300, height=100, mask='auto')

canvas.setFont('Helvetica', 32, leading=None)
canvas.drawCentredString(width / 2.0, 700, "Certificate of")

canvas.setFont('Courier', 24, leading=None)
canvas.drawCentredString(width / 2.0, 450, "Florian Kröber")

frame1 = Frame(width / 15.0, 80, 500, 300, showBoundary=0)

sp = ParagraphStyle('parrafos',
                    alignment=TA_CENTER,
                    fontSize=14,
                    fontName="Helvetica")
def render_claims_to_pdf(request, slug, claim_group, deferred_awards):
    """Currently hard-coded to print to Avery 22805 labels"""

    metrics = dict(
        page_width=(8.5 * inch),
        page_height=(11.0 * inch),
        top_margin=(0.5 * inch),
        left_margin=((25.0 / 32.0) * inch),
        qr_overlap=((1.0 / 32.0) * inch),
        padding=((1.0 / 16.0) * inch),
        horizontal_spacing=((5.0 / 16.0) * inch),
        vertical_spacing=((13.0 / 64.0) * inch),
        width=(1.5 * inch),
        height=(1.5 * inch),
    )

    debug = (request.GET.get('debug', False) is not False)

    pagesize = (metrics['page_width'], metrics['page_height'])
    cols = int((metrics['page_width'] - metrics['left_margin']) /
               (metrics['width'] + metrics['horizontal_spacing']))
    rows = int((metrics['page_height'] - metrics['top_margin']) /
               (metrics['height'] + metrics['vertical_spacing']))
    per_page = (cols * rows)
    label_ct = len(deferred_awards)
    page_ct = math.ceil(label_ct / per_page)

    pages = [
        deferred_awards[x:x + (per_page)]
        for x in range(0, label_ct, per_page)
    ]

    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    if not debug:
        # If debugging, don't force download.
        response['Content-Disposition'] = (
            'attachment; filename="%s-%s.pdf"' %
            (slug.encode('utf-8', 'replace'), claim_group))

    badge_img = None

    fout = StringIO()
    c = canvas.Canvas(fout, pagesize=pagesize)

    for page in pages:
        c.translate(metrics['left_margin'],
                    metrics['page_height'] - metrics['top_margin'])

        for row in range(0, rows, 1):
            c.translate(0.0, 0 - metrics['height'])
            c.saveState()

            for col in range(0, cols, 1):

                try:
                    da = page.pop(0)
                except IndexError:
                    continue

                if not badge_img:
                    image_fin = da.badge.image.file
                    image_fin.open()
                    badge_img = ImageReader(StringIO(image_fin.read()))

                c.saveState()
                render_label(request, c, metrics, da, badge_img, debug)
                c.restoreState()

                dx = (metrics['width'] + metrics['horizontal_spacing'])
                c.translate(dx, 0.0)

            c.restoreState()
            c.translate(0.0, 0 - metrics['vertical_spacing'])

        c.showPage()

    c.save()
    response.write(fout.getvalue())
    return response
예제 #22
0
 def _image(self, node):
     import urllib
     import urlparse
     from reportlab.lib.utils import ImageReader
     nfile = node.get('file')
     if not nfile:
         if node.get('name'):
             image_data = self.images[node.get('name')]
             _logger.debug("Image %s used", node.get('name'))
             s = StringIO(image_data)
         else:
             newtext = node.text
             if self.localcontext:
                 res = utils._regex.findall(newtext)
                 for key in res:
                     newtext = eval(key, {}, self.localcontext) or ''
             image_data = None
             if newtext:
                 image_data = base64.decodestring(newtext)
             if image_data:
                 s = StringIO(image_data)
             else:
                 _logger.debug("No image data!")
                 return False
     else:
         if nfile in self.images:
             s = StringIO(self.images[nfile])
         else:
             try:
                 up = urlparse.urlparse(str(nfile))
             except ValueError:
                 up = False
             if up and up.scheme:
                 # RFC: do we really want to open external URLs?
                 # Are we safe from cross-site scripting or attacks?
                 _logger.debug("Retrieve image from %s", nfile)
                 u = urllib.urlopen(str(nfile))
                 s = StringIO(u.read())
             else:
                 _logger.debug("Open image file %s ", nfile)
                 s = _open_image(nfile, path=self.path)
     try:
         img = ImageReader(s)
         (sx, sy) = img.getSize()
         _logger.debug("Image is %dx%d", sx, sy)
         args = {'x': 0.0, 'y': 0.0, 'mask': 'auto'}
         for tag in ('width', 'height', 'x', 'y'):
             if node.get(tag):
                 args[tag] = utils.unit_get(node.get(tag))
         if ('width' in args) and (not 'height' in args):
             args['height'] = sy * args['width'] / sx
         elif ('height' in args) and (not 'width' in args):
             args['width'] = sx * args['height'] / sy
         elif ('width' in args) and ('height' in args):
             if (float(args['width']) / args['height']) > (float(sx) > sy):
                 args['width'] = sx * args['height'] / sy
             else:
                 args['height'] = sy * args['width'] / sx
         self.canvas.drawImage(img, **args)
     finally:
         s.close()
예제 #23
0
 def render_sig(flowable, signature=datamatrix(bill.signature)):
     flowable.canv.drawImage(ImageReader(signature), 0, 0)
예제 #24
0
def testplot(names, showChannels, infile, outfile, approved):
    x = []
    ch1 = []
    ch2 = []
    ch3 = []
    ch4 = []
    ch5 = []
    ch6 = []
    ch7 = []
    ch8 = []

    with open(infile, 'r') as csvfile:
        plots = csv.reader(csvfile, delimiter=',')
        fig, ax = plt.subplots()

        df = pd.read_csv(infile,
                         sep='\s*,\s*',
                         encoding='ascii',
                         engine='python')
        #df.set_index("Time", inplace=True)
        #print(df.head())
        headers = df.columns.tolist()
        #print(headers)
        #for row in plots:
        #   ch1.append(int(row[1]))
        test = df[headers[0]]
        print(df[headers[0]].head())

    if showChannels[0] == 'true':
        plt.plot(df[headers[0]], df[headers[1]], label=headers[1])
    if showChannels[1] == 'true':
        plt.plot(df[headers[0]], df[headers[2]], label=headers[2])
    if showChannels[2] == 'true':
        plt.plot(df[headers[0]], df[headers[3]], label=headers[3])
    if showChannels[3] == 'true':
        plt.plot(df[headers[0]], df[headers[4]], label=headers[4])
    if showChannels[4] == 'true':
        plt.plot(df[headers[0]], df[headers[5]], label=headers[5])
    if showChannels[5] == 'true':
        plt.plot(df[headers[0]], df[headers[6]], label=headers[6])
    if showChannels[6] == 'true':
        plt.plot(df[headers[0]], df[headers[7]], label=headers[7])
    if showChannels[7] == 'true':
        plt.plot(df[headers[0]], df[headers[8]], label=headers[8])

    ax.xaxis.set_major_locator(plt.MaxNLocator(3))
    ax.set_ylim(0, 1000)
    plt.setp(ax.get_xticklabels())
    plt.xlabel('time')
    plt.grid()
    plt.ylabel('mbar')
    plt.legend()

    imgdata = BytesIO()
    plt.savefig(imgdata, format='png', dpi=1200)
    imgdata.seek(0)

    im = ImageReader(imgdata)
    logo = ImageReader('/home/larskf/TestReportGenerator/DB_long.jpg')

    c = canvas.Canvas(outfile)
    w, h = c._pagesize
    c.drawImage(im, 0, 120, w, h, preserveAspectRatio=True)
    c.drawImage(logo, 100, h / 2 - 50, w - 200, h, preserveAspectRatio=True)

    start = datetime.datetime.strptime(df[headers[0]].values[0],
                                       '%d.%m.%Y %H:%M:%S')
    stop = datetime.datetime.strptime(df[headers[0]].values[-1],
                                      '%d.%m.%Y %H:%M:%S')
    dur = stop - start

    c.setFont('Helvetica-Bold', 13)
    str = "Pressure leak test"
    c.drawString(50, 725, str)
    c.setFont('Helvetica', 11)

    str = "Started logging at:"
    c.drawString(50, 300, str)
    str = "     {}".format(start)
    c.drawString(50, 280, str)
    str = "Test duration: {}".format(dur)
    c.drawString(50, 260, str)

    c.drawString(
        50, 255,
        "_______________________________________________________________________________"
    )
    c.setFont('Helvetica', 9)
    if showChannels[0] == 'true':
        maxval = max(df[headers[1]])
        minval = min(df[headers[1]])
        avgval = statistics.mean(df[headers[1]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[1], maxval, minval, avgval, maxval - minval)
        #str = "%s:  Max: %f.2  Min: %f.2 Avg: %f.2 " % (names[0], maxval, minval, avgval)
        c.drawString(50, 240, str)

    if showChannels[1] == 'true':
        maxval = max(df[headers[2]])
        minval = min(df[headers[2]])
        avgval = statistics.mean(df[headers[2]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[2], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 220, str)
    if showChannels[2] == 'true':
        maxval = max(df[headers[3]])
        minval = min(df[headers[3]])
        avgval = statistics.mean(df[headers[3]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[3], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 200, str)
    if showChannels[3] == 'true':
        maxval = max(df[headers[4]])
        minval = min(df[headers[4]])
        avgval = statistics.mean(df[headers[4]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[4], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 180, str)
    if showChannels[4] == 'true':
        maxval = max(df[headers[5]])
        minval = min(df[headers[5]])
        avgval = statistics.mean(df[headers[5]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[5], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 160, str)
    if showChannels[5] == 'true':
        maxval = max(df[headers[6]])
        minval = min(df[headers[6]])
        avgval = statistics.mean(df[headers[6]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[6], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 140, str)
    if showChannels[6] == 'true':
        maxval = max(df[headers[7]])
        minval = min(df[headers[7]])
        avgval = statistics.mean(df[headers[7]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[7], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 120, str)
    if showChannels[7] == 'true':
        maxval = max(df[headers[8]])
        minval = min(df[headers[8]])
        avgval = statistics.mean(df[headers[8]])
        str = "{}:  Max: {:.0f} mbar     Min: {:.0f} mbar     Avg: {:.0f} mbar      Drop: {:.0f} mbar".format(
            headers[8], maxval, minval, avgval, maxval - minval)
        c.drawString(50, 100, str)

    c.drawString(
        50, 95,
        "_______________________________________________________________________________"
    )

    c.setFont('Helvetica', 11)
    str = "Approved by: %s" % approved
    c.drawString(50, 75, str)
    c.drawString(50, 30, "_____________________________________")

    c.save()
예제 #25
0
    def draw_image(
        self,
        img,
        x,
        y,
        width=None,
        height=None,
        proportional=True,
        scale=None,
        halign=None,
        valign=None,
    ):
        """
            Helper function to draw an image
            - requires PIL (required for ReportLab image handling anyway)

            @param img: the image (filename or BytesIO buffer)
            @param x: drawing position
            @param y: drawing position
            @param width: the target width of the image (in points)
            @param height: the target height of the image (in points)
            @param proportional: keep image proportions when scaling to width/height
            @param scale: scale the image by this factor (overrides width/height)
            @param halign: horizontal alignment ("left"|"center"|"right"), default left
            @param valign: vertical alignment ("top"|"middle"|"bottom"), default bottom
        """

        if hasattr(img, "seek"):
            is_buffer = True
            img.seek(0)
        else:
            is_buffer = False

        try:
            from PIL import Image as pImage
        except ImportError:
            current.log.error("Image rendering failed: PIL not installed")
            return

        pimg = pImage.open(img)
        img_size = pimg.size

        if not img_size[0] or not img_size[1]:
            # This image has at least one dimension of zero
            return

        # Compute drawing width/height
        if scale:
            width = img_size[0] * scale
            height = img_size[1] * scale
        elif width and height:
            if proportional:
                scale = min(
                    float(width) / img_size[0],
                    float(height) / img_size[1])
                width = img_size[0] * scale
                height = img_size[1] * scale
        elif width:
            height = img_size[1] * (float(width) / img_size[0])
        elif height:
            width = img_size[0] * (float(height) / img_size[1])
        else:
            width = img_size[0]
            height = img_size[1]

        # Compute drawing position from alignment options
        hshift = vshift = 0
        if halign == "right":
            hshift = width
        elif halign == "center":
            hshift = width / 2.0

        if valign == "top":
            vshift = height
        elif valign == "middle":
            vshift = height / 2.0

        # Draw the image
        if is_buffer:
            img.seek(0)
        ir = ImageReader(img)

        c = self.canv
        c.drawImage(
            ir,
            x - hshift,
            y - vshift,
            width=width,
            height=height,
            preserveAspectRatio=proportional,
            mask="auto",
        )
예제 #26
0
def _create_header(canvas, doc, draw_page_number=True):
    canvas.saveState()
    canvas.setTitle('Invoice')
    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y = PAGE_HEIGHT - HEADER_MARGIN

    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    canvas.drawImage(dpaw_header_logo,
                     PAGE_WIDTH / 3,
                     current_y - (dpaw_header_logo_size[1] / 2),
                     width=dpaw_header_logo_size[0] / 2,
                     height=dpaw_header_logo_size[1] / 2,
                     mask='auto')

    current_y -= 70
    canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE,
                             'TAX INVOICE')

    current_y -= 20
    canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE,
                             'ABN: 38 052 249 024')

    # Invoice address details
    invoice_details_offset = 37
    current_y -= 10

    invoice = doc.invoice
    proposal = doc.proposal
    bi = proposal.bookings.filter(
        invoices__invoice_reference=invoice.reference)
    licence_number = proposal.approval.lodgement_number if proposal.approval else None

    # TODO need to fix, since individual parks can be exempt, Below calculation assumes NO PARK IS exempt
    #is_gst_exempt = proposal.application_type.is_gst_exempt if proposal.fee_invoice_reference == invoice.reference else False

    canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
    current_x = PAGE_MARGIN + 5
    if proposal.org_applicant:
        canvas.drawString(current_x,
                          current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                          proposal.applicant)
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      invoice.owner.get_full_name())
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
                      invoice.owner.email)
    current_x += 452

    #write Invoice details
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      'Date')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      invoice.created.strftime(DATE_FORMAT))
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      'Page')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      str(canvas.getPageNumber()))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
        'Licence Number')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
                      licence_number)
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4,
        'Invoice Number')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4,
                      invoice.reference)
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
        'Total (AUD)')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
                      currency(invoice.amount))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
        'GST included (AUD)')
    canvas.drawString(
        current_x + invoice_details_offset,
        current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
        currency(invoice.amount - calculate_excl_gst(invoice.amount)
                 if not _is_gst_exempt(proposal, invoice) else 0.0))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7,
        'Paid (AUD)')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7,
                      currency(invoice.payment_amount))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 8,
        'Outstanding (AUD)')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 8,
                      currency(invoice.balance))

    if bi and bi[0].deferred_payment_date and invoice.payment_method in [
            invoice.PAYMENT_METHOD_MONTHLY_INVOICING,
            invoice.PAYMENT_METHOD_BPAY
    ]:
        canvas.drawRightString(
            current_x + 20,
            current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 9,
            'Payment Due Date')
        canvas.drawString(
            current_x + invoice_details_offset,
            current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 9,
            bi[0].deferred_payment_date.strftime(DATE_FORMAT))

    canvas.restoreState()
def _create_header(canvas, doc, draw_page_number=True):
    canvas.saveState()
    canvas.setTitle('Confirmation')
    canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE)

    current_y = PAGE_HEIGHT - HEADER_MARGIN

    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    canvas.drawImage(dpaw_header_logo,
                     PAGE_WIDTH / 3,
                     current_y - (dpaw_header_logo_size[1] / 2),
                     width=dpaw_header_logo_size[0] / 2,
                     height=dpaw_header_logo_size[1] / 2,
                     mask='auto')

    current_y -= 100
    #invoice = doc.invoice
    proposal = doc.proposal
    #licence_number = proposal.approval.lodgement_number if booking.proposal.approval else None

    PAGE_TITLE = 'AWAITING PAYMENT CONFIRMATION'
    canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE,
                             PAGE_TITLE)

    # Invoice address details
    invoice_details_offset = 37
    current_y -= 25
    canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE)
    current_x = PAGE_MARGIN + 5
    #canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),    proposal.applicant)
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      proposal.applicant)
    if hasattr(proposal.invoice,
               'payment_status') and proposal.invoice.payment_status in [
                   'paid', 'over_paid'
               ]:
        canvas.drawString(
            current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
            proposal.invoice.owner.get_full_name())
        canvas.drawString(
            current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
            proposal.invoice.owner.email)
    current_x += 435

    total_amount = 0.0
    if hasattr(proposal.invoice,
               'payment_status') and proposal.invoice.payment_status in [
                   'paid', 'over_paid'
               ]:
        pass
    else:
        # Calc Total Amount
        for item in proposal.filming_fees.last().lines:
            amount = float(item['price_incl_tax']) * item['quantity']
            total_amount += amount

    #write Invoice details
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
                      'Date')
    canvas.drawString(
        current_x + invoice_details_offset,
        current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),
        to_local_tz(proposal.filming_fees.last().created).strftime(DATE_FORMAT)
        + ' (AWST)')
    canvas.drawString(current_x,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      'Page')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,
                      str(canvas.getPageNumber()))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
        'Proposal Number')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,
                      proposal.lodgement_number)
    #if proposal.fee_invoice_reference:
    if proposal.filming_fee_invoice_reference:
        canvas.drawRightString(
            current_x + 20,
            current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Invoice')
        canvas.drawString(
            current_x + invoice_details_offset,
            current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4,
            proposal.filming_fee_invoice_reference)

    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
        'Payment Due Date')
    canvas.drawString(
        current_x + invoice_details_offset,
        current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5,
        proposal.filming_fees.last().deferred_payment_date.strftime(
            DATE_FORMAT))
    canvas.drawRightString(
        current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
        'Outstanding (AUD)')
    canvas.drawString(current_x + invoice_details_offset,
                      current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6,
                      currency(total_amount))
    #    if hasattr(booking, 'booking_type'):
    #        canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Booking No.')
    #        canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, booking.admission_number)
    canvas.restoreState()
예제 #28
0
파일: printer.py 프로젝트: opqopq/bgm_wx
def pdfcreate_image(deckname, dst, fitting_size, front,back, templates):
    output=canvas.Canvas(os.path.join(dst,deckname+".pdf"),psize,cropMarks=False)
    output.setTitle(deckname)
    output.setStrokeColor(black)
    output.setFont('Times-Roman',10)
    output.setPageCallBack(cb)
    import config
    if fitting_size is None:
        fitting_size=(config.px,config.py)
    else:
        fitting_size=[p2cm(i) for i in fitting_size]
    a4_size_x,a4_size_y=(config.a4x,config.a4y)
    x,y=fitting_size
    left=p2cm(config.left)
    right=p2cm(config.right)
    top=p2cm(config.top)
    bottom=p2cm(config.bottom)
    sheet_left=p2cm(config.sheet_left)
    sheet_top=p2cm(config.sheet_top)
    x_gap=left+right+x+p2cm(5)
    y_gap=top+bottom+y+p2cm(5)
    NUM_ROW=int((a4_size_x-top)/x_gap)
    NUM_COL=int((a4_size_y-left)/y_gap)
    PICT_BY_SHEET=NUM_COL*NUM_ROW
    deckname=deckname.lower().split('.')[0]
    if DEBUG:
        print 'Preparing %d picts by sheet (%d by %d)'%(PICT_BY_SHEET, NUM_ROW, NUM_COL),
        _t=""
        if dual: _t=" BACK mode"
        print _t
    maxlen=max(len(front),len(back))
    for i in range(int(ceil((float(maxlen)/PICT_BY_SHEET)))):
        for dual,imgs in zip((False,True),(front,back)):
            if not imgs:
                continue
            sheet_imgs=imgs[PICT_BY_SHEET*i:PICT_BY_SHEET*(i+1)]
            if not sheet_imgs:
                continue
            sheet_imgs.reverse()
            #Write the fiiting size info for deck + date
            from datetime import date
            text="Printed on the %s. fitting size: %s"%(date.today().strftime('%d/%m/%y'),fitting_size)
            output.drawString(sheet_left,a4_size_y-sheet_left,text)        
            for col in range(NUM_COL):
                for row in range(NUM_ROW):
                    try:
                        s,rotated,templateName,values=sheet_imgs.pop()
                        #print s,rotated,templateName,values
                        T=templates.get(templateName,None)
                        if not T:
                            #print templateName,T, templates.keys()
                            T= template_empty
                        #else:
                        #print 'using template',T.name
                        card=T.draw(os.path.join(config.card_folder,s.encode('cp1252')),fitting_size,values)
                    except IndexError:#done ! 
                        break
                    if rotated:
                        card=card.rotate(90)
    
                    #No more resizing: this is being handled by draw image bounding box                
                    card=card.resize([config.cm2p(_i) for _i in fitting_size])
    
                    #Start point is reverted from right border if dual
                    if not dual:
                        startx=row*x_gap + sheet_left
                    else:
                        startx=a4_size_x - ((row+1)*x_gap + sheet_left)
                    starty=col*y_gap + sheet_top
                    #Line vertical:
                    output.line(startx*cm,0,startx*cm,a4_size_y*cm)
                    output.line(cm*(startx+left+right+x),0,cm*(startx+left+right+x),a4_size_y*cm)
                    #Line horizontal
                    output.line(0,starty*cm,a4_size_x*cm,starty*cm)
                    output.line(0,(starty+top+bottom+y)*cm,a4_size_x*cm,(starty+top+bottom+y)*cm)
                    #~ #black rectangle
                    if config.BLACK_FILLING:
                        output.rect(startx*cm,starty*cm, (left+right+x)*cm, (top+bottom+y)*cm,fill=True)
                    #PAste image
                    c=StringIO()
                    card.save(c, format="PNG")
                    c.seek(0) #Rewind it
                    ir = ImageReader(c)
                    #print 'Pasting Image at cm:',startx+left,starty+top, x,y,fitting_size
                    output.drawImage(ir,(startx+left)*cm,(starty+top)*cm,x*cm,y*cm)
            output.showPage()
            #In dual mode, save as back
    output.save()
예제 #29
0
 def get_image(self, path, width):
     """Return image with a specified width and the original aspect ratio."""
     img = ImageReader(path)
     iw, ih = img.getSize()
     aspect = ih / float(iw)
     return Image(path, width=width, height=(width * aspect))
예제 #30
0
def create_pdf(person, ong):
    """method used to create the pdf

    person: dict with the person's data 
        first_name
        father
        last_name
        email
        tel
        street
        number
        bl
        sc
        et
        ap
        county
        city
        cnp


    ong: dict with the ngo's data
        name
        cif
        account
    """

    # packet = StringIO.StringIO()
    # we could also use StringIO
    packet = tempfile.TemporaryFile(mode='w+b')

    c = canvas.Canvas(packet, A4)
    width, height = A4

    # add the image as background
    background = ImageReader(abs_path + image_path)
    c.drawImage(background, 0, 0, width=width, height=height)

    # the default font size
    # info(c.getAvailableFonts())
    c.setFont('OpenSans', default_font_size)
    c.setFontSize(default_font_size)

    # the year
    # this is the previous year, starting from 1 Jan until - 25 May ??
    year = str(datetime.now().year - 1)
    start_x = 305
    for letter in year:
        c.drawString(start_x, 734, letter)
        start_x += 18

    # DRAW DONOR DATA
    if person:
        add_donor_data(c, person)

    # DRAW ONG DATA
    # if the ngo has a special status, the form is completed differently
    if ong['special_status']:
        add_special_status_ngo_data(c, ong)
    else:
        add_ngo_data(c, ong)

    c.save()

    # go to the beginning of the file
    packet.seek(0)
    # packet.type = "application/pdf"

    return packet