Exemplo n.º 1
0
def create_pdf(out_filename, a_file_location, a_number, receipt_number):
    c = canvas.Canvas(out_filename, pagesize=pagesizes.letter)

    c.setFont('Helvetica', 18)
    c.drawString(POS_X + 0.5, POS_Y_LOC, "A FILE LOCATION")
    c.setFont('Helvetica', 24)
    c.drawString(POS_X + 0.5, POS_Y_LOC - 0.5 * inch, a_file_location)

    c.setFont('Helvetica', 14)

    barcode_a_num = code128.Code128(a_number,
                                    barWidth=BAR_WIDTH,
                                    barHeight=BAR_HEIGHT)
    barcode_receipt_num = code128.Code128(receipt_number,
                                          barWidth=BAR_WIDTH,
                                          barHeight=BAR_HEIGHT)

    barcode_a_num.drawOn(c, POS_X, POS_Y_A_NUMBER)
    c.drawString(POS_X + 0.5 * inch, POS_Y_A_NUMBER - 0.25 * inch, a_number)

    barcode_receipt_num.drawOn(c, POS_X, POS_Y_RECEIPT_NUMBER)
    c.drawString(POS_X + 0.5 * inch, POS_Y_RECEIPT_NUMBER - 0.25 * inch,
                 receipt_number)

    c.showPage()

    c.save()
Exemplo n.º 2
0
    def _create_sticker_cell(self, code):
        """
        Creates the contents for a single cell
        """
        if isinstance(code, tuple):
            code, description = code
        else:
            code, description = code, code
        barcode = code128.Code128(code,
                                  barHeight=self.barcode_height,
                                  barWidth=self.barcode_width)
        data = [[barcode], [self._format_description(description)]]

        table = Table(data,
                      colWidths=(50 * mm),
                      rowHeights=(self.barcode_height - 1, 8 * mm))
        style = TableStyle([('FONTSIZE', (0, 0), (-1, -1), 3 * mm),
                            ('LEFTPADDING', (0, 0), (-1, -1), 0),
                            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                            ('TOPPADDING', (0, 0), (-1, 0), 1 * mm),
                            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                            ('VALIGN', (0, -1), (-1, -1), 'MIDDLE')])
        table.setStyle(style)
        return table
Exemplo n.º 3
0
    def _create_sticker(self):
        """
        Creates a single sticker page.
        """
        barcode = code128.Code128(self.code,
                                  barHeight=self.barcode_height,
                                  barWidth=self.barcode_width)
        data = [[barcode], [self._format_description(self.description)]]
        table = Table(data,
                      colWidths=self.sticker_width,
                      rowHeights=(self.sticker_height / 2) - 1 * mm)
        style = TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 12),
            ('LEFTPADDING', (0, 0), (-1, -1), 0),
            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
            ('TOPPADDING', (0, 0), (-1, -1), 1),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
            ('FONT', (0, 0), (-1, -1), 'Tahoma'),
            #('GRID', (0, 0), (-1, -1), 1, colors.CMYKColor(black=60)),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER')
        ])
        table.setStyle(style)

        return table
Exemplo n.º 4
0
def createBarCodes(c, barcode_value):
    # 条码生成
    barcode128 = code128.Code128(barcode_value)
    barcode128.barWidth = 1.1
    barcode128.drawOn(c, -7.15, 15)
    # 字符添加
    c.setFont(
        'Helvetica-Bold',
        9,
    )
    c.drawString(35, 3, barcode_value)
    # 二维码生成
    qrstr = QR_Prefix + barcode_value
    qr_code = qr.QrCodeWidget(qrstr)
    bounds = qr_code.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(
        45,
        40,
        transform=[45. / (width - 15), 0, 0, 45. / (height - 15), 0, 0])
    d.add(qr_code)
    renderPDF.draw(d, c, 60, 33)
    # 添加图片
    c.drawImage('.\img\img.jpg', 12.85, 40)
Exemplo n.º 5
0
def login(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="login.pdf"'

    barcode_size = [
        int(x)
        for x in request.GET.get("barcode_size", "43x25").strip().split("x")
    ]
    pw, ph = barcode_size[0], barcode_size[1]

    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=(pw * mm, ph * mm))

    pk = int(request.GET.get("pk", "-1"))
    u = DoctorProfile.objects.filter(user__pk=pk).first()
    if u and (not u.user.is_staff or request.user.is_staff):
        barcode = code128.Code128(u.get_login_id(),
                                  barHeight=ph * mm - 8 * mm,
                                  barWidth=0.265 * mm)
        barcode.drawOn(c, -4 * mm, 6.1 * mm)
        c.setFont('clacon', 15)
        c.drawCentredString(pw * mm / 2, 2 * mm, u.get_fio(dots=False))
    c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
Exemplo n.º 6
0
def create_label_response(label_data: LabelData, number=1):
    """create label and return response object with PDF label file"""
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="{}-barcode.pdf"'.format(
        label_data.serial_number)
    barcode = code128.Code128(label_data.serial_number,
                              barHeight=10 * mm,
                              barWidth=0.211 * mm,
                              quiet=False)
    page = canvas.Canvas(response)
    page.setPageSize((51 * mm, 30 * mm))

    for i in range(number):
        page.setFontSize(6)
        page.drawString(2 * mm, 27 * mm, 'Model: {}'.format(label_data.model))
        page.drawString(2 * mm, 24 * mm, 'Color: {}'.format(label_data.color))
        page.drawString(2 * mm, 21 * mm,
                        'Item No./SKU: {}'.format(label_data.sku))
        page.drawString(7 * mm, 16 * mm,
                        'Serial No: {}'.format(label_data.serial_number))

        barcode.drawOn(page, 2 * mm, 5 * mm)
        page.lines([(2 * mm, 4 * mm, 49 * mm, 4 * mm),
                    (2 * mm, 18.5 * mm, 49 * mm, 18.5 * mm)])
        page.drawString(
            2 * mm, 1 * mm,
            '{}: {}'.format(label_data.date_field_name,
                            label_data.date.strftime("%d.%m.%Y")))
        page.showPage()
    page.save()

    return response
Exemplo n.º 7
0
    def barcode(self, uuid):
        """ Generate barcode of uuid """

        barcode = code128.Code128(str(uuid), barWidth=1, barHeight=20)
        barcode.drawOn(self.canvas, self.lastx, self.lasty)
        self.lasty = self.lasty - 20
        self.y = self.lasty
Exemplo n.º 8
0
def geraPagina(formato, numeros, c, pagesize, SHOW_BORDER=True, pular=0):
    w, h = pagesize
    i = 0
    for linha in range(formato['Linhas']):
        for coluna in range(formato['Colunas']):
            i += 1
            try:
                numero = numeros[linha][coluna]
            except IndexError:
                return
            x = formato['Esquerda']*cm + (formato['Horizontal']*cm * coluna)
            y = h - formato['Superior']*cm - (formato['Vertical']*cm * (linha) +1)
            import string
            string = string.uppercase * 4
            string = numero.descricao
            c.drawString(x+4*mm, y+(20*mm), string[0:21])
            c.drawString(x+24*mm, y+(15*mm), string[21:35])
            c.drawString(x+24*mm, y+(10*mm), string[35:49])
            c.drawString(x+24*mm, y+(5*mm), string[49:64])
            if SHOW_BORDER:
                c.rect(x, y, formato['Largura']*cm, formato['Altura']*cm)
        
            if len(numero.codigo) == 1:
                codigo = "000%d" % int(numero.codigo)
            else:
                codigo = numero.codigo
            barcode = code128.Code128(codigo, barWidth=0.26*mm, barHeight=13*mm, 
                                      quiet=False, humanReadable=True)
            barcode.drawOn(c, x+(1*mm)+(4*mm), y+(4*mm))
Exemplo n.º 9
0
def createBarCodes():
    """
    Create barcode examples and embed in a PDF
    """
    c = canvas.Canvas("barcodes.pdf", pagesize=A4)

    barcode_value = "1234567890"

    barcode39 = code39.Extended39(barcode_value)
    barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1)

    # code93 also has an Extended and MultiWidth version
    barcode93 = code93.Standard93(barcode_value)

    barcode128 = code128.Code128(barcode_value)
    # the multiwidth barcode appears to be broken
    #barcode128Multi = code128.MultiWidthBarcode(barcode_value)

    barcode_usps = usps.POSTNET("50158-9999")

    codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps]

    x = 1 * mm
    y = 285 * mm
    x1 = 6.4 * mm

    for code in codes:
        code.drawOn(c, x, y)
        y = y - 15 * mm

    # draw the eanbc8 code
    barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value)
    bounds = barcode_eanbc8.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(50, 10)
    d.add(barcode_eanbc8)
    renderPDF.draw(d, c, 15, 555)

    # draw the eanbc13 code
    barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value)
    bounds = barcode_eanbc13.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(50, 10)
    d.add(barcode_eanbc13)
    renderPDF.draw(d, c, 15, 465)

    # draw a QR code
    qr_code = qr.QrCodeWidget(
        'https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python'
    )
    bounds = qr_code.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0])
    d.add(qr_code)
    renderPDF.draw(d, c, 15, 405)

    c.save()
Exemplo n.º 10
0
 def _create_supply_section(self):
     """
     Creates the higher level order section
     
     This section will also contain a subsection of 
     the items for this order
     """     
     data = [["PREVIEW", 'ID', "BARCODE", "TYPE", "DESCRIPTION"]]   
     
     for supply in self.queryset:
         
         try:
             image = self.get_image(supply.image.generate_url(), width=100)
         except AttributeError:
             image = ""
         except IOError:
             image = "Image NA"
             
         data.append([image,
                      supply.id,
                      code128.Code128("DRS-{0}".format(supply.id), 
                                      barHeight=20),
                      supply.type, 
                      self._prepare_text(supply.description)])
    
         
     table = Table(data, colWidths=[110, 50, 100, 75, 200], repeatRows=1)
     table.setStyle(TableStyle(self.table_style))
         
     return table
Exemplo n.º 11
0
 def put_corner_right_data(self, pdf):
     pdf.setFont('Times-Bold', 12)
     pdf.drawString(350, 810, 'R.U.C ' + self.object.company_id.vat[2:])
     pdf.drawString(350, 790, self.name)
     pdf.drawString(350, 770, 'No. ' + self.object.number)
     pdf.setFont('Times-Bold', 10)
     pdf.drawString(350, 750, 'NUMERO DE AUTORIZACION')
     pdf.setFont('Times-Roman', 9)
     pdf.drawString(350, 730, self.object.electronic_authorization)
     pdf.setFont('Times-Bold', 10)
     env = 'PRODUCCION'
     if self.object.env['webservice.sri'].get_webservice_sri(
     ).environment == '1':
         env = 'PRUEBAS'
     pdf.drawString(
         350, 710, 'Fecha y hora de autorizacion: ' +
         self.format_date(self.object.authorization_date or ''))
     pdf.drawString(350, 690, 'Ambiente: ' + env)
     pdf.drawString(350, 670, 'Emision: Normal')
     pdf.setFontSize(10)
     pdf.drawString(350, 655, 'CLAVE DE ACCESO')
     barcode = code128.Code128(self.object.access_key)
     barcode.drawOn(pdf, 350, 625)
     pdf.setFont('Times-Roman', 8)
     pdf.drawString(355, 610, self.object.access_key)
     pdf.rect(330, 600, 250, 230)
     return pdf
Exemplo n.º 12
0
def createBarCodes():
    """
    Create barcode examples and embed in a PDF
    """
    c = canvas.Canvas("barcodes.pdf", pagesize=letter)

    barcode_value = "12345678999M"

    barcode39 = code39.Extended39(barcode_value)
    barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1)

    # code93 also has an Extended and MultiWidth version
    barcode93 = code93.Standard93(barcode_value)

    barcode128 = code128.Code128(barcode_value)
    # the multiwidth barcode appears to be broken
    #barcode128Multi = code128.MultiWidthBarcode(barcode_value)

    barcode_usps = usps.POSTNET("50158-9999")

    codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps]

    x = 1 * mm
    y = 260 * mm
    x1 = 6.4 * mm

    for code in codes:
        code.drawOn(c, x, y)
        y = y - 30 * mm
    barcode_value = "123456789990"

    # draw the eanbc8 code
    barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value)
    bounds = barcode_eanbc8.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(50, 10)
    d.add(barcode_eanbc8)
    renderPDF.draw(d, c, 150 * mm, 150 * mm)

    # # draw the eanbc13 code
    barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value)
    bounds = barcode_eanbc13.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(50, 10)
    d.add(barcode_eanbc13)
    renderPDF.draw(d, c, 150 * mm, 100 * mm)

    # # draw a QR code
    qr_code = qr.QrCodeWidget('www.ghf.com')
    bounds = qr_code.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0])
    d.add(qr_code)
    renderPDF.draw(d, c, 150 * mm, 50 * mm)

    c.save()
Exemplo n.º 13
0
 def add_bar_code(self, x, y, text):
     """
         Metodo utilizado para crear un codigo de barra dentro del pdf
     """
     pdf_canvas = self.__get_object_pdf_canvas()
     barcode128 = code128.Code128(text)
     barcode128.drawOn(pdf_canvas, x, y)
     return self
Exemplo n.º 14
0
 def codeimg(self):
     if settings.QRCODE:
         border = self.template.border_qr or (0 if self.template.is_vertical
                                              else 4)
         return QRFlowable(self.code, border=border)
     return code128.Code128(self.code,
                            barWidth=0.01 * inch,
                            barHeight=0.5 * inch)
Exemplo n.º 15
0
    def _create_header(self, canvas, doc):
        #Draw the logo in the upper left
        if self.company.lower() == 'dellarobbia thailand':
            path = """https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/form_logo.jpg"""
        else:
            path = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/Alinea-Logo_Master.jpg"
        
        # Read image from link
        img = utils.ImageReader(path)
        
        # Get Size
        img_width, img_height = img.getSize()
        new_width = (img_width * logo_height) / img_height
        canvas.drawImage(path, 42, 760, height=logo_height, width=new_width)

        canvas.setFont('Helvetica', 8)
        canvas.setFillColorCMYK(0, 0, 0, 60)
        #Add Company Information in under the logo if dellarobbia
        if self.company.lower() == 'dellarobbia thailand':
            canvas.drawString(42, 760,
                            "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka")
            canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150")
            canvas.drawString(42, 740, "+66 2 508 8681")
        else:
            canvas.drawString(42, 760,
                            "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka")
            canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150")
            canvas.drawString(42, 740, "+66 2 508 8681")
        #canvas.drawString(42, 730, "www.dellarobbiathailand.com")

        # Create The document type and document number
        canvas.setFont("Helvetica", 16)
        canvas.drawRightString(550, 800, 'Purchase Order')
        canvas.setFont("Helvetica", 12)
        canvas.drawRightString(550, 780, 'PO# : {0}'.format(self.id))

        # Create a barcode from the id
        canvas.setFillColorCMYK(0, 0, 0, 1)
        code = 'PO-{0}'.format(self.id)
        barcode = code128.Code128(code, barHeight=20, barWidth=0.5 * mm)
        x_position = 570 - barcode.width
        # drawOn puts the barcode on the canvas at the specified coordinates
        barcode.drawOn(canvas, x_position, 750)
        
        # Create the revision
        if self.revision:
            if self.revision_date:
                msg = u"Revision: {0}, # {1}"
                revision_str = msg.format(self.revision_date.strftime('%B %d, %Y'),
                                          self.revision)
            else:
                msg = u'Revision: # {0}'
                revision_str = msg.format(self.revision)
                
            canvas.setFillColorCMYK(0, 0, 0, 1)
            canvas.setFont("Helvetica", 12)
            canvas.drawRightString(550, 730, revision_str)
Exemplo n.º 16
0
def code128_demo(barcode_value):
    doc = SimpleDocTemplate('code128_demo.pdf')
    styles = getSampleStyleSheet()
    flowables = []

    flowables.append(Paragraph('Code 128:', style=styles['Normal']))
    barcode128 = code128.Code128(barcode_value)
    flowables.append(barcode128)

    doc.build(flowables)
    def plotarEtiquetas(object, coluna, linha):
        # Descrição do Produto
        desc = object.getDesc()
        # Limitando o tamanho da string para 25
        if (len(desc) > 25):
            desc = desc[:25]
        # Definindo o valor referente à topologia da plotagem
        ajuste_desc = switchCase_desc(desc)
        # Plotando o nome do produto
        PDF.drawString(x=margemXInicial + ajuste_desc +
                       ((larguraEtiqueta + 0.2 * cm) * coluna),
                       y=tamanhoVertical - margemYInicial - (0.5 * cm) -
                       (alturaEtiqueta * linha),
                       text=desc)

        # BarCode
        barCode = object.getBarcode()
        # Verificando se o código tem até 14 caracteres
        if (len(str(barCode)) > 14):
            print('Tamanho excede 14 dígitos, perdendo centralização')
        # Transformando o código em string
        ajuste_barCode = switchCase_barCode(str(barCode))
        # Transformando código em barras
        barCode = code128.Code128(barCode)
        # Plotando o código de barras
        barCode.drawOn(PDF,
                       x=margemXInicial + ajuste_barCode +
                       ((larguraEtiqueta + 0.2 * cm) * coluna),
                       y=tamanhoVertical - margemYInicial - (1.3 * cm) -
                       (alturaEtiqueta * linha))

        # Cod
        cod = str(object.getCod())
        #Verificando o tamanho do código
        if (len(cod) > 10):
            print('Código excede 10 dígitos')
        ajuste_cod = switchCase_code(cod)
        # Plotando o Código numeral
        PDF.drawString(x=margemXInicial + ajuste_cod +
                       ((larguraEtiqueta + 0.2 * cm) * coluna),
                       y=tamanhoVertical - margemYInicial - (1.55 * cm) -
                       (alturaEtiqueta * linha),
                       text=cod)

        # Preço
        preco = str(object.getValor()[:-1])
        ajuste_preco = switchCase_preco(preco)
        # Plotando o preço do produto

        PDF.drawString(x=margemXInicial + ajuste_preco +
                       ((larguraEtiqueta + 0.2 * cm) * coluna),
                       y=tamanhoVertical - margemYInicial - (1.9 * cm) -
                       (alturaEtiqueta * linha),
                       text='R$ ' + preco)
Exemplo n.º 18
0
def create_sku_bar_code(info):
    c = canvas.Canvas('C:\Users\Administrator\Desktop\\' + info+'.pdf')
    print c.getAvailableFonts()

    c.setPageSize((51*mm, 76*mm))

    barcode = code128.Code128(info, barHeight=6.3*mm, barWidth=42*mm)
    barcode.drawOn(c, 6.3*mm, 10*mm)
    # c.drawString(2*mm, 6*mm, '1111') #写名字
    # c.drawString(2 * mm, 6 * mm, info)  # 写名字
    c.showPage()
    c.save()
Exemplo n.º 19
0
def create_sku_bar_code1(info):
    c = canvas.Canvas('C:\Users\Administrator\Desktop\\' + info+'.pdf')
    c.setPageSize((76*mm, 51*mm))

    barcode = code128.Code128(info)
    barcode.drawOn(c, 1*mm, 40*mm)

    c.drawString(6.3*mm, 35*mm, info)
    c.drawString(6.3*mm, 30*mm, '1')

    c.showPage()
    c.save()
Exemplo n.º 20
0
    def _create_products_item_section(self, product):
        data = []
        #add the data
        data.append([
            code128.Code128("DRAI-{0}".format(product.id),
                            barHeight=20), product.description,
            product.unit_price, product.quantity, product.total
        ])

        #Add comments if they exists
        if product.comments:
            style = ParagraphStyle(name='Normal',
                                   fontName='Garuda',
                                   leading=12,
                                   wordWrap='CJK',
                                   allowWidows=1,
                                   allowOrphans=1,
                                   fontSize=10,
                                   textColor=colors.black)
            paragraph = Paragraph(product.comments.replace('\n', '<br/>'),
                                  style)
            comments = Table([['  Comments:', paragraph]], colWidths=(60, 235))
            comments.setStyle(
                TableStyle([('FONT', (0, 0), (-1, -1), 'Garuda'),
                            ('FONTSIZE', (0, 0), (-1, -1), 10),
                            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black)]))
            data.append(['', comments, ''])

        #Create table
        table = Table(data, colWidths=(80, 300, 60, 40, 65))
        style_data = [
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            #Lines around content
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.CMYKColor(black=80)),
            ('LINEAFTER', (0, 0), (-1, -1), 1, colors.black),
            ('LINEBEFORE', (0, 0), (0, -1), 1, colors.black),
            ('FONT', (0, 0), (-1, -1), 'Garuda'),
            #General alignment
            ('ALIGNMENT', (0, 0), (1, -1), 'CENTER'),
            #Align description
            ('ALIGNMENT', (1, 0), (1, -1), 'LEFT'),
            #Align Unit Price
            ('ALIGNMENT', (-3, 0), (-3, -1), 'RIGHT'),
            #Align Quantity
            ('ALIGNMENT', (-2, 0), (-2, -1), 'CENTER'),
            #align totals to the right
            ('ALIGNMENT', (-1, 0), (-1, -1), 'RIGHT')
        ]
        style = TableStyle(style_data)
        table.setStyle(style)
        return table
Exemplo n.º 21
0
 def _flowable(self, node, extra_style=None):
     if node.tag == 'para':
         style = self.styles.para_style_get(node)
         if extra_style:
             style.__dict__.update(extra_style)
         result = []
         for i in self._textual(node).split('\n'):
             result.append(
                 platypus.Paragraph(
                     i, style,
                     **(utils.attr_get(node, [], {'bulletText': 'str'}))))
         return result
     elif node.tag == 'barCode':
         try:
             from reportlab.graphics.barcode import code128
             from reportlab.graphics.barcode import code39
             from reportlab.graphics.barcode import code93
             from reportlab.graphics.barcode import common
             from reportlab.graphics.barcode import fourstate
             from reportlab.graphics.barcode import usps
         except Exception, e:
             return None
         args = utils.attr_get(
             node, [], {
                 'ratio': 'float',
                 'xdim': 'unit',
                 'height': 'unit',
                 'checksum': 'int',
                 'quiet': 'int',
                 'width': 'unit',
                 'stop': 'bool',
                 'bearers': 'int',
                 'barWidth': 'float',
                 'barHeight': 'float'
             })
         codes = {
             'codabar': lambda x: common.Codabar(x, **args),
             'code11': lambda x: common.Code11(x, **args),
             'code128': lambda x: code128.Code128(x, **args),
             'standard39': lambda x: code39.Standard39(x, **args),
             'standard93': lambda x: code93.Standard93(x, **args),
             'i2of5': lambda x: common.I2of5(x, **args),
             'extended39': lambda x: code39.Extended39(x, **args),
             'extended93': lambda x: code93.Extended93(x, **args),
             'msi': lambda x: common.MSI(x, **args),
             'fim': lambda x: usps.FIM(x, **args),
             'postnet': lambda x: usps.POSTNET(x, **args),
         }
         code = 'code128'
         if node.get('code'):
             code = node.get('code').lower()
         return codes[code](self._textual(node))
Exemplo n.º 22
0
def bcode(Elements, textarg, codearg):
    Elements.append(Paragraph(textarg, styles['Heading2']))
    val = textarg
    barwidth = .0170 * inch
    barcode = code128.Code128(codearg,
                              quiet=1,
                              barWidth=barwidth,
                              barHeight=.50 * inch)
    Elements.append(barcode)
    style = styles['Normal']
    style.leftIndent = .25 * inch
    Elements.append(Paragraph(codearg, style))
    return Elements
Exemplo n.º 23
0
def createBarCodes(i):
    """
    Create barcode examples and embed in a PDF
    """
    #c = canvas.Canvas("/tmp/barcodes.pdf", pagesize=letter)
    buff = BytesIO()
    c = canvas.Canvas(buff, pagesize=letter)
    pdfmetrics.registerFont(TTFont('FreeSans', 'FreeSans.ttf'))
    c.setFont("FreeSans",12)

    a=5
    b=-10
    cc=5
    y = 780
    d=0
    next_page=0
    barcode128 = code128.Code128(i.pid)
    c.drawString(cc,y,'ИП Мелай О.В')
    y = y - 7 * mm
    barcode128.drawOn(c,b,y)
    y = y - 5 * mm
    c.drawString(cc,y,i.pid)
    y = y - 5 * mm
    c.drawString(cc,y,i.description)
    y = y - 5 * mm
    c.drawString(cc,y,'%s руб.' % str(i.price))
    y = y - 5 * mm
    d=d+1
    next_page=next_page+1
    if d == 10:
        y=780
        a=a+130
        b=b+130
        cc=cc+130
        d=0
        #if next_page == 36:
    if next_page == 50:
        c.showPage()
        c.setFont("FreeSans",12)
        a=5
        b=-10
        cc=5
        y = 780
        next_page=0

    c.save()
    pdf = buff.getvalue()
    buff.close()
    return pdf
Exemplo n.º 24
0
    def _create_header(self, canvas, doc):
        #Draw the logo in the upper left
        if self.company.name.lower() == u'dellarobbia thailand':
            path = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/Alinea-Logo_Master.jpg"
        else:
            path = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/Alinea-Logo_Master.jpg"

        #Read image from link
        img = utils.ImageReader(path)
        #Get Size
        img_width, img_height = img.getSize()
        new_width = (img_width * logo_height) / img_height
        canvas.drawImage(path, 42, 760, height=logo_height, width=new_width)

        #Add Company Information in under the logo
        canvas.setFont('Helvetica', 8)
        canvas.setFillColorCMYK(0, 0, 0, 1)

        #Add Company Information in under the logo if dellarobbia
        if self.company.name.lower() == u'dellarobbia thailand':
            canvas.drawString(
                42, 760,
                "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka")
            canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150")
            canvas.drawString(42, 740, "+66 2 508 8681")
        else:
            canvas.drawString(
                42, 760,
                "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka")
            canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150")
            canvas.drawString(42, 740, "+66 2 508 8681")
            canvas.drawString(42, 730, "Tax ID: 0105560020175")

        #Create The document type and document number
        canvas.setFont("Helvetica", 16)
        canvas.drawRightString(550, 800, 'RECEIPT')
        canvas.setFont("Helvetica", 12)
        canvas.drawRightString(550, 780, 'Receipt#: {0}'.format(self.id))
        #Create a barcode from the id
        canvas.setFillColorCMYK(0, 0, 0, 1)
        code = "RV-{0}".format(self.id)
        barcode = code128.Code128(code, barHeight=20, barWidth=0.5 * mm)
        x_position = 570 - barcode.width
        # drawOn puts the barcode on the canvas at the specified coordinates
        barcode.drawOn(canvas, x_position, 750)
Exemplo n.º 25
0
    def _create_sticker_cell(self, employee):
        """
        Creates the contents for a single cell
        """
        code = "DREM-{0}".format(employee.id)
        logger.debug(employee.id)
        if employee.first_name and employee.last_name:
            description = u"{0} {1}".format(employee.first_name,
                                            employee.last_name)
        elif employee.first_name and not employee.last_name:
            description = u"{0}".format(employee.first_name)
        elif not employee.first_name and not employee.last_name:
            description = u"{0}".format(employee.name)

        barcode = code128.Code128(code,
                                  barHeight=self.barcode_height,
                                  barWidth=0.3 * mm)

        try:
            data = [[
                self._get_image(employee.image.generate_url(time=1800000),
                                height=20 * mm),
                self._format_description(description)
            ], [barcode]]
        except AttributeError:
            data = [["", self._format_description(description)], [barcode]]

        table = Table(data,
                      colWidths=(25 * mm, 30 * mm),
                      rowHeights=(self.sticker_height - self.barcode_height,
                                  self.barcode_height))
        style = TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 3 * mm),
            ('SPAN', (0, 1), (1, 1)),
            ('LEFTPADDING', (0, 0), (-1, -1), 0),
            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
            ('TOPPADDING', (0, 0), (-1, 0), 1 * mm),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            #('GRID', (0, 0), (-1, -1), 1, colors.CMYKColor(magenta=60)),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('ALIGN', (1, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
        ])
        table.setStyle(style)
        return table
Exemplo n.º 26
0
 def _create_prop_item(self, prop):
     data = [
         self._get_image(prop.image.generate_url(), width=70), prop.id,
         code128.Code128("Prop-{0}".format(prop.id), barHeight=20),
         prop.reference,
         float(prop.cost) * 5.07
     ]
     table = Table([data], colWidths=(70, 50, 100, 100, 100))
     style_data = [
         ('TEXTCOLOR', (0, 0), (-1, -1), colors.CMYKColor(black=60)),
         ('GRID', (0, 0), (-1, 0), 1, colors.CMYKColor(black=60)),
         #General alignment
         ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'),
         ('VALIGN', (0, 0), (-1, -1), 'TOP')
     ]
     style = TableStyle(style_data)
     table.setStyle(style)
     return table
Exemplo n.º 27
0
    def print_code_128(self,
                       x,
                       y,
                       text,
                       hauteur=20,
                       largeur=1,
                       font_size=6,
                       human_readable=1):
        """
		Insert un code 128
		"""
        barcode128 = code128.Code128(text,
                                     barHeight=hauteur,
                                     barWidth=largeur,
                                     fontSize=font_size,
                                     human_readable=human_readable,
                                     quiet=0)
        barcode128.drawOn(self.canvas, x * mm, y * mm)
Exemplo n.º 28
0
 def _barcode(self, node):
     createargs = {}
     drawargs = {}
     code_type = node.getAttribute('code')
     for tag in ('x', 'y'):
         if node.hasAttribute(tag):
             drawargs[tag] = utils.unit_get(node.getAttribute(tag))
     if code_type == 'Code128':
         for tag in ('barWidth', 'barHeight'):
             if node.hasAttribute(tag):
                 createargs[tag] = utils.unit_get(node.getAttribute(tag))
         barcode = code128.Code128(self._textual(node), **createargs)
     elif code_type == "QR":
         for tag in ('width', 'height'):
             if node.hasAttribute(tag):
                 createargs[tag] = utils.unit_get(node.getAttribute(tag))
         barcode = qr.QrCode(node.getAttribute('value'), **createargs)
     barcode.drawOn(self.canvas, **drawargs)
Exemplo n.º 29
0
 def createBarCodes(
 ):  #Unsure of the benefits downsides of using extended vs standard?
     if len(dfl('catalogNumber')) > 0:
         barcodeValue = dfl('catalogNumber')
     else:
         barcodeValue = self.settings.dummyCatNumber
     if barcodeValue:
         barcode128 = code128.Code128(
             barcodeValue,
             barHeight=(self.yPaperSize * .10),
             barWidth=((self.xPaperSize * 0.28) /
                       (len(barcodeValue) * 13 + 35)),
             humanReadable=True,
             quiet=False,
             checksum=0)
         #^^^Note width is dynamic, but I don't know the significe of *13+35 beyond making it work.
         return barcode128
     else:
         return ''
Exemplo n.º 30
0
def geraPagina(formato, numeros, c, pagesize):
    w, h = pagesize
    for linha in range(formato['Linhas']):
        for coluna in range(formato['Colunas']):
            try:
                numero = numeros[linha][coluna]
            except IndexError:
                return
            x = formato['Esquerda'] * cm + (formato['Horizontal'] * cm *
                                            coluna)
            y = h - formato['Superior'] * cm - (formato['Vertical'] * cm *
                                                (linha + 1))
            if SHOW_BORDER:
                c.rect(x, y, formato['Largura'] * cm, formato['Altura'] * cm)
            barcode = code128.Code128(numero,
                                      barWidth=0.26 * mm,
                                      barHeight=13 * mm,
                                      quiet=False,
                                      humanReadable=True)
            barcode.drawOn(c, x + (1 * mm), y + (4 * mm))