Пример #1
0
def genera_boletos(rango):
    font2 = ImageFont.truetype("/home/francisco/Carousel.ttf", 60)
    font = ImageFont.truetype("/home/francisco/gunplay3.ttf", 120)
    generar_imagen_font('Boleto', font2, 'boleto.png')
    p = Usb(0x04b8, 0x0202)
    sa = "niñoññ"
    for x in rango:
        nombre_imagen = 'a_number{}.png'.format(x)
        generar_imagen_font(str(x), font, nombre_imagen)
        p.set(align='center', font='b')
        p.charcode(code="NORDIC")
        p.image("FantasyWorld.png")
        p.text(
            "Venta de articulos de belleza,  cosmeticos,  regalos, y  juguetes."
            + "\n\n")
        p.image("boleto.png")
        p.image(nombre_imagen)
        p.text(
            "Fantasy  les  desea  una  feliz  navidad y prospero anio nuevo\n")
        p.text(
            "La rifa se llevara a cabo el dia 6 de enero del 2018 a  las 12:00 pm\n"
        )
        p.text("Gracias por su preferencia\n")
        p.cut()
        p.image("boleto.png")
        p.image(nombre_imagen)
        p.text("\n________________________________________" + "\n")
        p.text("Nombre\n\n")
        p.set(align='center', font='a')
        p.text("Deposite este boleto en la urna")
        p.cut()
Пример #2
0
def print_thermal(header, title_first, title_seconds, date_time, qr_code,
                  gate_info, type_scan):
    result = False
    try:
        p = Usb(int(CONFIG['PRINTER']['vid'], 0),
                int(CONFIG['PRINTER']['pid'], 0),
                int(CONFIG['PRINTER']['timeout'], 0),
                int(CONFIG['PRINTER']['ep1in'], 0),
                int(CONFIG['PRINTER']['ep1out'], 0))
        p.set("CENTER", "B", "A", 2, 2)
        p.text(str(header) + "\n\n")
        p.set("CENTER", "A", "normal", 1, 1)
        p.text(str(title_first) + "\n")
        p.text(str(title_seconds) + "\n")
        p.text(str(date_time) + "\n\n")
        if (type_scan == 0):
            p.qr(str(qr_code), 0, 10)
        else:
            p.barcode(str(qr_code), "CODE128", function_type="B")
        p.text("\nPintu Masuk : " + str(gate_info) +
               "\n*** TERIMAKASIH ***\n\n\n")

        result = True
    except Exception as e:
        print(e)

    return result
Пример #3
0
def print_instructions(instructions):
    """
    Print instructions to a thermal printer.
    :param instructions: list of strings containing the instructions
    """

    try:
        # Vendor ID and Product ID of the 36-pin IEEE 1284 to USB converter,
        # this printer is so old it doesn't have USB directly
        printer = Usb(0x1a86, 0x7584, profile="TM-T88II")
    except Exception as e:
        print("Exception while trying to access printer via USB:")
        print(str(e))
        try:
            printer = File("/dev/usb/lp0", profile="TM-T88II")
        except FileNotFoundError as e:
            print(
                "Received exception while trying to access printer via File:")
            print(str(e))
            return

    # print header
    printer.set(custom_size=True, width=4, height=3)
    printer.textln(" Reparatur")
    printer.textln(" anweisung")
    printer.set()  # reset to default
    printer.ln(2)

    for instruction in instructions:
        printer.textln(instruction)
        printer.ln()
    printer.image(ASSETS_PATH / "images/combined.png", center=True)
    printer.ln()
    printer.cut()
Пример #4
0
def printReport(details):

#    p = Usb(0x04B8, 0x0E15, 0)
    p = Usb(0x0416, 0x05011, 0)
    p.set(align='center', width=1, height=2)
    p.text("Maker's Account Information\n\n")
    p.set(align='left', text_type='B', width=1, height=1)
    p.text(details['result']['user']['fullName'] + '\n')
    p.set(align='left')
    p.text('User name: ' + details['result']['user']['username'] + '\n')
    p.text(details['result']['user']['email'] + '\n')
    p.text('Phone: ' + details['result']['user']['phone'] + '\n')

    p.text('\nRegistered to vote: ')
    p.set(text_type='B')
    voting_rights_label = "Voting Members"
    if voting_rights_label in details['result']['user']['groups']:
        p.text('Yes')
    else:
        p.text('No')
    p.set(align='left')
    p.text('\n')

    p.text('\nAuthorized Equipment List\n')
    p.text('(Please report any omissions)\n\n')
    for element in details['result']['user']['groups']:
        p.text(element + '\n')
    p.text('\n\n\n')
Пример #5
0
def printStickerLabel(orderNumber):
    stickerPrinter = Usb(0x1ba0, 0x220a, 0)
    stickerPrinter.set("center")

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    # mycursor = mydb.cursor()
    # mycursor.execute("UPDATE orderPlaced SET collected  = IF(made = 1, 1 , 0), made  = IF(made = 0, 1 , 1) WHERE orderID = " + str(orderNumber))
    mycursor = mydb.cursor()
    mycursor.execute("SELECT IF(collected = 1, 'Collected' , 'Made') as Output, count(orderLine.extras), IF(orderPlaced.paid,'Paid On App','NEEDS TO PAY'), orderPlaced.orderID, orderPlaced.collection, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderPlaced.orderID = " + str(orderNumber))
    myresult = mycursor.fetchall()
    for x in myresult:
        for z in range(1,int(x[1]+1)):
            stickerPrinter.text(" Order Complete  \n")
            stickerPrinter.text(str(x[3]) + "\n\n")
            stickerPrinter.text(str(x[2]) + "\n\n")
            stickerPrinter.text(" Collection Time  \n")
            stickerPrinter.text(str(x[4]) + "\n\n")
            stickerPrinter.text("" + str(z) + " of " + str(int(x[1])) + "\n")
            stickerPrinter.barcode(str(x[3]), 'CODE39', 64, 2, 'OFF', 'True')
            if z != x[1]:
                stickerPrinter.text("\n\n=======================\n\n")
            else:
                stickerPrinter.cut()
    stickerPrinter.close()
Пример #6
0
class Peripherals:
    def __init__(self):
        self.printer = Usb(0x0416, 0x5011, profile="POS-5890")
        self.scanner = InputDevice(
            '/dev/input/event0')  # Replace with your device

        self.scancodes = {
            11: u'0',
            2: u'1',
            3: u'2',
            4: u'3',
            5: u'4',
            6: u'5',
            7: u'6',
            8: u'7',
            9: u'8',
            10: u'9'
        }

    def start_scanner(self, cbfunc):
        print("Starting scanner thread!")
        self.scanner_thr = BaseThread(name='scanner_thr',
                                      target=self.scanner_func,
                                      callback=cbfunc)
        self.scanner_thr.start()

    def scanner_func(self):
        barcode = ''
        # Make a thread
        for event in self.scanner.read_loop():
            if event.type == ecodes.EV_KEY:
                eventdata = categorize(event)
                # Keydown
                if eventdata.keystate == 1:
                    scancode = eventdata.scancode
                    # Enter
                    if scancode == 28:
                        # get the barcode (barcode)
                        return barcode
                    else:
                        key = self.scancodes.get(scancode, NOT_RECOGNIZED_KEY)
                        barcode = barcode + key
                        if key == NOT_RECOGNIZED_KEY:
                            print('unknown key, scancode=' + str(scancode))

    def start_print(self, time, order_number, barcodes):
        self.printer.set(align='left')
        self.printer.text("Time : %s \n" % time)
        self.printer.text("No Order : %s \n" % order_number)
        self.printer.text("Gate : 1")
        self.printer.text('\n')
        self.printer.soft_barcode('code128',
                                  barcodes,
                                  module_height=8,
                                  module_width=0.18)
        self.printer.text('\n')

        print("Done printing!")
Пример #7
0
def printInitalOrderTicket(newValue):
    receiptPrinter = Usb(0x04b8, 0x0202, 0)
    receiptPrinter.set("center")

    EAN = barcode.get_barcode_class('code128')

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    mycursor = mydb.cursor()
    mycursor.execute("SELECT lineID FROM orderLine WHERE orderID = " + str(newValue))
    myresult = mycursor.fetchall()
    orderlineIDS = []
    for x in myresult:
        orderlineIDS.append(str(x).split("(")[1].split(",")[0])

    complete = []	

    for x in orderlineIDS:
        mycursor = mydb.cursor()
        sql = "SELECT orderPlaced.orderID, DATE_FORMAT(orderPlaced.time, '%D %M %Y %T'), orderPlaced.collection, (SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.foodID AND orderLine.lineID = " + str(x) + ") AS baguette, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.snackID AND orderLine.lineID = " + str(x) + ") AS snack, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.drinkID AND orderLine.lineID = " + str(x) + ") AS drink, orderLine.extras, orderLine.sauces, orderPlaced.paid, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderLine.lineID = " + str(x)
        print(sql)
        mycursor.execute(sql)
        myresult = mycursor.fetchall()
        complete.append(myresult)
        
    receiptPrinter.image("/home/pi/Documents/logo.png")
    receiptPrinter.text("\n\nNew Order Received\n")
    receiptPrinter.text("Order Number: " + str(complete[0][0][0]) + "\n\n")
    receiptPrinter.text("Date: " + str(complete[0][0][1]) + "\n\n")
    receiptPrinter.text("***************************************\n\n")
    for x in complete:
        receiptPrinter.text(str(x[0][3]).title() + " Baguette\n")
        receiptPrinter.text("(" + str(x[0][6]) + ")\n")
        receiptPrinter.text("(" + str(x[0][7]) + ")\n\n")
        if str(x[0][4]) != "None":
            receiptPrinter.text(str(x[0][4])+ "\n")
            receiptPrinter.text(str(x[0][5]) + "\n\n")  
        receiptPrinter.text("*\n\n")

    ean = EAN(str(complete[0][0][0]), writer=ImageWriter())
    fullname = ean.save('/home/pi/ean13_barcode')
    receiptPrinter.image("/home/pi/ean13_barcode.png")
    receiptPrinter.cut()
    mydb.close()
    """if str(complete[0][0][8]) == "0":
        client = Izettle(
            client_id='ccfe6b88-67e1-4f6d-94c5-34b91b11a5fa',
            client_secret='IZSEC33534207-7d83-4f70-b64d-8c54d4e21f00',
            user='******',
            password='******'
        )
        client.create_product_variant('d62f7bb0-2728-11e6-85b5-dd108c223139',{"name": "Order " + str(complete[0][0][0]) , "barcode": str(complete[0][0][0]), "price": {"amount": str(complete[0][0][9]), "currencyId": "GBP"}})
"""
    receiptPrinter.close()
Пример #8
0
class ThermalPrinter():
    def __init__(self):
        self.p = Usb(0x0fe6, 0x811e, 98, 0x82, 0x02)

    def insert_imagen(self, img_surce):
        self.p.image(img_surce)

    def insert_qr(self, content, size):
        self.p.qr(content, size=size)  #size 1 - 16 default 3

    def insert_barcode(self, code, bc, height, width):
        self.p.barcode(code, bc, height=height, width=width)

    def insert_text(self, txt):
        self.p.text(txt)

    def insert_raw_txt(self, txt):
        self.p._raw(txt)

    # harware action, may be: INIT, SELECT, RESET
    def hardware_operation(self, hw):
        self.p.hw(hw)

    #string for the following control sequences:
    # LF for Line Feed
    # FF for Form Feed
    # CR for Carriage Return
    # HT for Horizontal Tab
    # VT for Vertical Tab
    #pos = horizontal tab position 1 - 16
    def feed_control(self, ctl, pos):
        self.p.control()

        self.p.charcode()


#   #def insert_textln(self, txt):
# align = CENTER LEFT RIGHT  default left
# font_type = A or B         default A
# textt_type = B(bold), U(underline), U2(underline, version2), BU(for bold and underlined, NORMAL(normal text) defaul tnormal
# width = width multiplier decimal 1 - 8 defaul 1
# heigh =  height multiplier decimal 1 - 8 defaul 1
# density = density 0 - 8
# def set_txt(self, align, font, text_type, density, height, width):

    def set_txt(self, *args, **Kwargs):
        print(Kwargs)
        self.p.set(Kwargs)

    def cut_paper(self):
        self.p.cut()
Пример #9
0
class Print(object):
	def __init__(self):
		self.p = Usb(0x28e9, 0x0289, 0, out_ep=0x03)
	
	def __str__(self):
		return 
		
	__repr__ = __str__

	def cut(self):
		self.p.cut()
	
	def setText(self, size):
		self.p.set(align = u'center', font = u'a', smooth = True, width = size, height = size)

	def putImage(self, imagePath):
		self.p.image(str(imagePath))

	def putQr(self, qrInfo, qrSize = 10):
		self.p.qr(qrInfo, size = qrSize)

	def putBarcode(self, barcodeInfo):
		self.barcode(barcodeInfo, 'EAN13', 64, 2, '', '')

	def putText(self, text, textSize = 1):
		self.setText(textSize)
		self.p.text(text)

	def printResult(self, weight, volume, density):
		self.putText("******************************\n")
		self.putText(time.asctime())
		self.putText("\n")
		self.putText("\n")
		self.putText("Measured results are as follows:\n")
		self.putText("\n")
		self.putText("Weight: ")
		self.putText(str(weight))
		self.putText("\n")
		self.putText("Volume: ")
		self.putText(str(volume))
		self.putText("\n")
		self.putText("Density: ")
		self.putText(str(density))
		self.putText("\n")
		self.putText("\n")
		self.putText("Scan qr to check the result!\n")
		self.putQr("Weight: {weight}\nVolume: {volume}\nDensity: {density}".format(weight = weight, volume = volume, density = density))
		self.cut()
Пример #10
0
    def printLinux(self, dialog):
        """Print the passed dialog.

        Linux doesn't have raspberry pi drivers for the printer, so if running
        on a raspberry pi print with this method
        """
        painter = QPainter()

        p = dialog.palette()
        p.setColor(dialog.backgroundRole(), Qt.white)

        dialog.setPalette(p)

        width = dialog.getSize()[0]

        height = dialog.getSize()[1]

        scale = 2.2

        pixmap = QImage(width * scale, height * scale,
                        QImage.Format_Grayscale8)

        painter.begin(pixmap)
        painter.scale(scale, scale)
        dialog.render(painter)
        painter.end()

        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        pixmap.save(buffer, "PNG")
        pixmap.save("Hi.png", "PNG")  # just for testing

        strio = io.BytesIO()
        strio.write(buffer.data())
        buffer.close()
        strio.seek(0)
        pil_im = Image.open(strio)

        buffer = None

        p = Usb(0x04b8, 0x0e03, 0)
        p.image
        p.set(align='center')
        p.image(pil_im, impl="bitImageRaster", fragment_height=3000)
        p.cut()
Пример #11
0
def reprintOrderTicket(orderNumber):
    receiptPrinter = Usb(0x04b8, 0x0202, 0)
    receiptPrinter.set("center")

    EAN = barcode.get_barcode_class('code128')

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    mycursor = mydb.cursor()
    mycursor.execute("SELECT `lineID` FROM `orderLine` WHERE `orderID`= " + str(orderNumber))
    myresult = mycursor.fetchall()

    complete = []

    for x in myresult:
        x = x[0]
        mycursor = mydb.cursor()
        mycursor.execute("SELECT orderPlaced.orderID, DATE_FORMAT(orderPlaced.time, '%D %M %Y %T'), orderPlaced.collection, (SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.foodID AND orderLine.lineID = " + str(x) + ") AS baguette, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.snackID AND orderLine.lineID = " + str(x) + ") AS snack, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.drinkID AND orderLine.lineID = " + str(x) + ") AS drink, orderLine.extras, orderLine.sauces, orderPlaced.paid, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderLine.lineID = " + str(x))
        myresult = mycursor.fetchall()
        complete.append(myresult)
        
    receiptPrinter.text("REPRINT ORDER TICKET\n")
    receiptPrinter.text("Order Number: " + str(complete[0][0][0]) + "\n\n")
    receiptPrinter.text("Date: " + str(complete[0][0][1]) + "\n")
    receiptPrinter.text("***************************************\n\n")
    for x in complete:
        receiptPrinter.text(str(x[0][3]).title() + " Baguette\n")
        receiptPrinter.text("(" + str(x[0][6]) + ")\n")
        receiptPrinter.text("(" + str(x[0][7]) + ")\n\n")
        if str(x[0][4]) != "None":
            receiptPrinter.text(str(x[0][4])+ "\n")
            receiptPrinter.text(str(x[0][5]) + "\n\n\n")  

    receiptPrinter.text("\n")
    ean = EAN(str(complete[0][0][0]), writer=ImageWriter())
    fullname = ean.save('/home/pi/ean13_barcode')
    receiptPrinter.image("/home/pi/ean13_barcode.png")
    receiptPrinter.cut()
    mydb.close()
    
    receiptPrinter.close()
Пример #12
0
def generate_recipt(orderjson):
    p = Usb(0x0483, 0x5720, 0)

    #p.image("chainhack.png", high_density_vertical=True, high_density_horizontal=True)

    p.set(align='center',
          smooth=True,
          invert=True,
          density=8,
          width=4,
          height=4,
          font='1')
    p.text("Chainhack 4\n")
    p.set(align='center',
          smooth=True,
          invert=False,
          density=4,
          width=4,
          height=4)
    p.text("The Block\n")
    p.set(align='center',
          smooth=True,
          invert=False,
          density=4,
          width=4,
          height=4)
    p.text("Lisbon\n")
    '''
    p.set(align='left', smooth=True, invert=False, density=2, width=1, height=1)
    p.text("===========================\n")
    p.text("=============== Sales Recipt ===========\n")
    p.text("===========================\n")
    '''
    items = orderjson.get('items')

    print(items)
    '''
Пример #13
0
from escpos.printer import Usb
p = Usb(0x04b8,0x0202)
p.text("Hello World\n")
p.cut()
p.text("Saludos Mexico\n")
p.barcode('1324354657687','EAN13',34,2,'','')
 p.set(font='c')
p.cut()

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from escpos.printer import Usb
p = Usb(0x04b8,0x0202)

# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("/home/francisco/gunplay3.ttf",110)
img=Image.new("RGBA", (300,120),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"$30.00",(0,0,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
p.barcode('1324354657687','EAN13',34,2,'','')
p.image("a_test.png")
p.cut()
Пример #14
0
def printSpanish(date, guid, city, state, receiptId, leader, cashier, subtotal, tax, total, payments, eventType, Items, Cashes, Cards):


    temp = leader.strip().split(' ')
    leader = ""
    for x in range(len(temp)):
        if (len(temp[x]) > 0):
            leader = leader + " " + temp[x].strip()

    event =   "Seminario  : " + city.strip() + ", " + state.strip()
    leader =  "Lider      : " + trimHeader( leader.strip() )
    cashier = "Cajero     : " + cashier.strip()



    #stuff
    """ Seiko Epson Corp. Receipt Printer M129 Definitions (EPSON TM-T88IV) """
    p = Usb(0x04b8,0x0202,0)
    p.set("Center")

    p.image( os.path.dirname(os.path.realpath(__file__)) + "/logo.jpg")

    p.text(date + "\n")
    p.barcode( receiptId.strip() , "EAN13")
    p.text("\n")

    p.set("left")
    p.text(event + "\n")
    p.text(leader + "\n")
    p.text(cashier + "\n")
    p.text("\n")


    p.set("left")

    #				22		       3   4   3   5
    #       1234567890123456789011   1234     12345
    p.text("Producto                 Qty     Precio\n")
    #       Items[x][0]              Items[x][1] + " " + Items[x][2] + "\n")

    for x in range(len(Items)):
        #print repr(trimPrice[x][2])
	p.text( u''.join( trimName( Items[x][0] )  + trimQty( Items[x][1] ) + trimPrice( Items[x][2] ) + "\n") )

    if len(Cards) > 0:
        p.set("center")
        p.text("\n")
        p.text("=====Pagos De Tarjeta=====")
        p.text("\n\n")
        p.set('left')

        for card in Cards:
            cardStr =           "Tipo De Tarjeta        : " + card[0] + "\n"
            cardStr = cardStr + "Numero De Cuenta       : " + card[1] + "\n"
            cardStr = cardStr + "Nombre En La Tarjeta   : " + card[2].strip() + "\n"
            cardStr = cardStr + "Codigo de Autorizacion : " + card[3] + "\n"
            cardStr = cardStr + "ID de transaccion      : " + card[4] + "\n"
            cardStr = cardStr + "Cantidad               : " + trimPrice( str(card[5]) ) + "\n"
            cardStr = cardStr + "\n"
            p.text(cardStr)


            imgData = r''.join( card[7].strip().strip("\n") )
            imgData = "%r" % imgData

            with open("curr_signature.png", "wb") as fh:
                fh.write(base64.decodestring(imgData))


            img = Image.open( os.path.dirname(os.path.realpath(__file__)) + "/curr_signature.png")
            new_width  = 100
            new_height = 50
            img = img.resize((new_width, new_height), Image.ANTIALIAS)
            img.save('curr_signature.png') # format may what u want ,*.png,*jpg,*.gif

            p.set("center")
            p.image(  os.path.dirname(os.path.realpath(__file__)) + "/curr_signature.png" )
            p.set("left")

    if len(Cashes) > 0:
        p.set('center')
        p.text("\n")
        p.text('=====Pagos En Efectivo=====')
        p.text("\n\n")
        p.set('left')
        for cash in Cashes:
            cashStr =           "Efectivo Recibido  : " +  trimPrice ( str( cash[0]) )  + "\n"
            cashStr = cashStr + "Cambio             : " +  trimPrice ( str( cash[1]) ) + "\n"
            cashStr = cashStr + "\n"
            p.text(cashStr)



    p.text("\n\n\n")
    p.set("right")
    p.text("Total parcial   : " + trimBottomRight( trimPrice( str(subtotal) ) )   + "\n")
    p.text("Impuestos       : " + trimBottomRight( trimPrice( str(tax) ) )         + "\n")
    p.text("Total           : " + trimBottomRight( trimPrice( str(total) ) )       + "\n\n")

    p.set("Center", "A","B")
    p.text("Gracias!\n")
    p.set("Center", "A", "normal")
    p.text("Customer Copy\n")
    p.cut()
Пример #15
0
# -*- coding:utf-8 -*-
from usb.core import USBError  # device is offline or busy when printing
from escpos.exceptions import USBNotFoundError  # 实例化的时候
from escpos.printer import Usb
import barcode as Barcode
p = Usb(0x8866, 0x0100, timeout=0, out_ep=0x02)

p.set(align="CENTER")
p.text(" ")
p.text(u"机器编号: xyz-robot-001\n".encode("gbk"))
p.text("------------------------\n")
p.text("2020/09/01  13:01\n\n")
p.set(align="LEFT")
p.text(u"货架编号: xyz081010002\n".encode("gbk"))
p.text(u"\n格口位置:\n\t行数: 3\n\t列数: 3\n".encode("gbk"))
p.set(align="CENTER")
p.image("/home/xyz/code.png")
p.cut()
p.close()

# TODO 启动前检查纸带
# TODO 打印过程中缺纸,如何解决
Пример #16
0
from escpos.printer import Usb
from escpos import *
from time import sleep

# Adapt to your needs
p = Usb(0x0471, 0x0055, timeout=0, in_ep=0x82, out_ep=0x02)
#~ p = escpos.Escpos(0x0471, 0x0055,0)
# Print software and then hardware barcode with the same content
# p.soft_barcode('code39', '123456')

for idx in range(1):
    p.set(align='center', font='b', width=2, height=2)
    p.text('Ricevuta numero {}\n'.format(idx + 1))
    p.text('\n')
    p.set(align='left', font='c', width=3, height=3)
    p.text('Hello world\n')
    p.image('logo_bn.png')
    p.text('\n')
    p.set(align='right', font='a', width=1, height=1)
    p.text('Boxoffice LTC\n')
    p.text('\n')
    p.barcode('123456', 'CODE39')
    #~ p.print_and_feed(n=2)
    p.text('\n')
    p.qr("Prenotazione 00056", )
    p.text('\n')

    sleep(1)
    p.cut(mode=u'FULL')
Пример #17
0
def imprimir_ticket_final(data = {}, num_participantes=0):
    """
    Data = diccionario {id:num}
    :param data:
    :return:
    """
    p = Usb(0x04b8, 0x0e15, 0, )

    p.image("{}functions/cabecera.jpg".format(path_proyecto))
    p.set(font='a', height=1, align='center')
    p.codepage = 'cp850'
    try:
        p.text('Presupuestos Participativos de Inversiones 2018\n')
        p.text('- Acta de recuento - \n')

        p.text('----------------------------------- \n')
        p.set(font='a', height=2, align='center')
        # date = datetime.now()
        date = datetime.now() + timedelta(hours=2)
        p.text('Recuento realizado: \n {} \n \n'.format(date.strftime("%Y-%m-%d %H:%M:%S")))
        p.set(font='a', height=2, align='center')
        p.text('Participantes: {} personas\n \n'.format(num_participantes))
        p.text('Total de proyectos votados: {} proyectos \n \n'.format(len(data)))
        p.text('Proyectos votados: \n \n')
        p.set(font='a', height=1, align='center')
        if len(data) == 0:
            p.text("Lista vacia")
        #propuestas
        for i in data:
            e = propuestas.search_name_by_id(i)
            if e is None:
                print("Id de proyecto {} no valido".format(i))

            else:
                title, price = e
                votos = data[i]
                if votos == 1:
                    p.text('{} - {} voto \n\n'.format(title, votos))
                else:
                    p.text('{} - {} votos \n\n'.format(title, votos))

        p.set(font='a', height=1, align='center')
        p.text('----------------------------------- \n')
        p.set(font='a', height=1, align='center')
        p.text(
            'Sistema presencial de votación electrónica \n')
        p.text("Evotebox \n")
        p.image("{}functions/gente.png".format(path_proyecto))
        p.cut()
        p.close()
    except:
        # print(traceback.format_exc())
        p.cut()
        p.close()
Пример #18
0
valor = json_data['valor']
cliente = json_data['cliente']
atendente = json_data['atendente']
observacao = json_data['observacao']

qtd_compras = int(json_data['qtd_compras'])
compras_list = []
for i in range(qtd_compras):
	data_aux = json_data['compra_data' + str(i)]
	valor_aux = json_data['compra_valor' + str(i)]
	compras_list.append([data_aux, valor_aux])


# recibo do cliente

printer.set(align='center', width=2, height=2, invert=True)
printer.text(' Paes & Cia \n\n')

printer.set(align='center', width=2, height=1)
printer.text('Recibo de\npagamento\n\n')

printer.set(align='left', width=1, height=1)
printer.text('ID: ' + id_pagamento + '\n')
printer.text('Data: ' + data + '\n')
printer.text('Valor total: R$ ' + valor + '\n')
printer.text('Cliente: ' + cliente + '\n')
printer.text('Atendente: ' + atendente + '\n')
if (observacao != 'null'):
	printer.text('Observacao: ' + observacao + '\n')

printer.text('\n')
                #print dayly_entry_list
        else:
            dayly = False
            if '\n' and ':' not in item:
                entry += str(item + " ")
            else:
                if len(entry) > 0:
                    entry = entry.replace('\n','')
                    entry_list.append(entry)
                entry_list.append(item)
                entry = ""
entry = entry.replace('\n','')
entry_list.append(entry)
#print entry_list
Printer = Usb(0x0416,0x5011)
Printer.set(align=u'center', font=u'a', width=2, height=2, density=9, invert=False, smooth=True, flip=False)
Printer.text(title+"\n")
Printer.set(align=u'center', font=u'a', width=1, height=1, density=9, invert=False, smooth=True, flip=False)
if len(dayly_entry_list) > 0:
    Printer.text("\n------- Heute -------\n\n")
Printer.set(align=u'right', font=u'a', width=1, height=1, density=9, invert=False, smooth=True, flip=False)
for item in dayly_entry_list:
    try:
        Printer.text('{:3s}  {:>27s}'.format( "[ ]", item) + "\n\n")
    except UnicodeDecodeError:
        print "Error by Item:" + item
Printer.set(align=u'center', font=u'a', width=1, height=1, density=9, invert=False, smooth=True, flip=False)
if len(entry_list) > 1:
    Printer.text("\n------- Tasks -------\n\n")
Printer.set(align=u'right', font=u'a', width=1, height=1, density=9, invert=False, smooth=True, flip=False)
for item in entry_list:
Пример #20
0
def printOrder(data):
    try:
        p = Usb(0x0519, 0x000b)
        p.set(align=u'center')
        p.image("/var/www/loncheando/lonch1.png", impl=u'bitImageColumn')
        p.set(align=u'center', font=u'b', height=2, width=2)
        p.text(" \n")
        p.text("ORDEN: ")
        p.text(data["billCaiCurrentCaiAssigned"] + " \n")
        p.text(
            datetime.strptime(data["billDate"], "%Y-%m-%d %H:%M:%S").strftime(
                '%I:%M %p. %b %d,%Y') + " \n")
        p.text("Hora de entrega: ")
        p.text(data["billDeliveryHour"] + " \n")
        p.text("TEL: " + data["billDetailBusinessPhone"] + " \n \n")
        p.set(align=u'left', font=u'a', height=1, width=1)
        p.text("CLIENTE: ")
        p.text(removeData(data["billClientCompleteName"] + " \n"))
        p.text("CELULAR: ")
        p.text(data["billClientPhoneNumber"] + " \n \n")
        p.set(align=u'center', font=u'a', height=1, width=1)
        p.text("DETALLE DE ORDEN\n")

        for d in data["billDetail"]:
            p.text("__________________________________________\n \n")
            p.set(align=u'left', font=u'a', height=1, width=1)
            p.text("PRODUCTO:\n")
            p.set(align=u'right', font=u'a', height=1, width=1)
            p.text(removeData(d["billDetailProductName"]) + " \n \n")
            p.set(align=u'left', font=u'a', height=1, width=1)
            p.text("CANTIDAD: ")
            p.text(str(d["billDetailQuantity"]) + " \n \n")
            if d["billDetailOrderComments"] != "":
                p.text("DESCRIPCION:\n")
                p.set(align=u'right', font=u'a', height=1, width=1)
                p.text(removeData(d["billDetailOrderComments"]) + " \n")

        p.text("__________________________________________\n \n")
        p.set(align=u'right', font=u'a', height=1, width=1)
        p.text("TOTAL DE PRODUCTOS: ")
        p.text(str(data["billDetailQuantity"]) + " \n \n")
        p.set(align=u'left', font=u'b', height=2, width=2)
        p.text("DESCRIPCION DE LA ORDEN:\n")
        p.set(align=u'right', font=u'b', height=2, width=2)
        p.text(removeData(data["billOrderComments"]) + " \n")
        p.text(" \n")
        p.text(" \n")
        p.text(" \n")
        p.text(" \n")
        p.cut()
    except AssertionError as error:
        print(error)
        print("no se pudo imprimir")
Пример #21
0
printer = Usb(0x0416, 0x5011)


id_compra = json_data['id_compra']
data = json_data['data']
valor = json_data['valor']
cliente = json_data['cliente']
observacao = json_data['observacao']


cliente = unidecode(cliente)
atendente = unidecode(atendente)
observacao = unidecode(observacao)
    

printer.set(align='center', width=2, height=2)
printer.text('Paes & Cia\n\n')

printer.set(align='center', width=2, height=1)
printer.text('Recibo de\nentrega\n\n')

printer.set(align='left')
printer.text('ID: ' + id_compra + '\n')
printer.text('Data: ' + data + '\n')
printer.text('Valor: R$ ' + valor + '\n')
printer.text('Cliente: ' + cliente + '\n')
if (observacao != 'null'):
	printer.text('Observacao: ' + observacao + '\n')

printer.text('\n\n')
printer.set(align='center')
Пример #22
0
def checkout_setup(checkout_id):
    p = Usb(0x471, 0x55, 0, 0x82, 0x02)

    # p.device.read(p.in_ep, 1)

    res = requests.get('http://www.e-orders.org/api/printer/checkout-print?checkout_id={0}'.format(checkout_id))
    res_json = json.loads(res.text)
    print('response', res_json)
    items = res_json[0]
    print(items)

    p.set(align='center', text_type='B', width=3, height=3)
    p.text('CHECKOUT'+"\n")

    p.set(align='center', text_type='B', width=2, height=2)
    p.text(items['table_name']+"\n")
    p.set(align='center', text_type='normal', width=1, height=1)
    p.text(items['datetime']+"\n")

    for item in items['items']:
        p.set(align='left', text_type='B', width=2, height=1)
        p.text(str(item['quantity']) + 'x  '+ item['name']+'\n')
        p.set(align='right', text_type='B', width=1, height=1)
        p.text(str(item['quantity']) + ' x '+str(item['cost']) + '  sub total: ' + str(item['total_item_cost']) + '$' + '\n')
        # comment = item['comments']
    p.set(align='center', text_type='B', width=3, height=3)
    p.text('TOTAL: '+str(items['total'])+"\n")
    # p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    # p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    p.text('\n\n\n')
    # p.text('\n\n\n')
    p.cut()

    p.close()
Пример #23
0
def order_setup(order_id):
    myconverter = Converter(max_expansions=4)

    p = Usb(0x471, 0x55, 0, 0x82, 0x2)
    # p.codepa
    # p.device.write(p.out_ep, CHARCODE_GREEK, 5000)

    # p = Usb(0x1d6b, 0x2, 0, 0x82, 0x2)
    # p.codepage = 'cp1253'
    # p.charcode(code='AUTO')
    # p.device.read(p.in_ep, 1)

    res = requests.get('http://www.e-orders.org/api/app/order?order_id={0}'.format(order_id))
    res_json = json.loads(res.text)
    items = res_json['items']
    print(items)

    p.set(align='center', text_type='B', width=3, height=3)
    p.text('NEW ORDER'+"\n")

    p.set(align='center', text_type='B', width=2, height=2)
    p.text(items['items'][0]['table_name']+"\n")
    p.set(align='center', text_type='normal', width=1, height=1)
    p.text(items['datetime']+"\n")

    for item in items['items']:
        item_name =myconverter.convert(item['name'])[0]

        p.set(align='left', text_type='B', width=2, height=1)
        # p.text(str(item['quantity'])+'X '+item['name']+'\n')
        p.text(str(item['quantity'])+'X '+item_name+'\n')
        comment = item['comments']

        p.set(align='center', text_type='normal', width=1, height=1)
        print(comment)
        if comment =='':
            pass
        else:
            p.text('COMMENTS: '+item['comments'] + "\n")

        p.set(align='center', text_type='normal', width=2, height=1)

        for content in item['contents']:
            if content['changed'] == 1:
                if content['default'] == 0:
                    p.text('WITH   '+content['content_name']+'\n')

    p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    p.cut()
    # RT_STATUS = DLE + EOT
    # RT_STATUS_ONLINE = RT_STATUS + b'\x01'
    # RT_STATUS_PAPER = RT_STATUS + b'\x04'
    # p.barcode()
    method_list = [func for func in dir(p) if callable(getattr(p, func))]
    # print('device: ', p.query_status(PAPER_FULL_CUT))
    # print('device: ', p.query_status(PAPER_FULL_CUT))
    e = "\x10\x04\x04"
    # p.device.write(p.out_ep, RT_STATUS_PAPER)
    print('device: ', )
    print('device: ', )
    # print('device: ', p._raw(RT_STATUS_ONLINE))
    # print('device: ', p._read())
    p.close()
Пример #24
0
    icon = data['currently']['icon']
    image = GRAPHICS_PATH + icon + ".png"
    return image


deg = ' C'      # Degree symbol on thermal printer, need to find a better way to use a proper degree symbol

# if you want Fahrenheit change units= to 'us'
url = "https://api.darksky.net/forecast/" + API_KEY + "/" + LAT + "," + LONG + \
    "?exclude=[alerts,minutely,hourly,flags]&units=si"  # change last bit to 'us' for Fahrenheit
response = urllib.urlopen(url)
data = json.loads(response.read())

printer.print_and_feed(n=1)
printer.control("LF")
printer.set(font='a', height=2, align='center', bold=True, double_height=True)
printer.text("Weather Forecast")
printer.text("\n")
printer.set(align='center')


# Print current conditions
printer.set(font='a', height=2, align='center', bold=True, double_height=False)
printer.text('Current conditions: \n')
printer.image(icon())
printer.text("\n")

printer.set(font='a', height=2, align='left', bold=False, double_height=False)
temp = data['currently']['temperature']
cond = data['currently']['summary']
printer.text(temp)
Пример #25
0
import os
import asyncio
from iZettle.iZettle import Izettle, RequestException
import slack
import ssl as ssl_lib
import certifi
import mysql.connector
from escpos.printer import Usb
import barcode
from barcode.writer import ImageWriter
import threading

EAN = barcode.get_barcode_class('code128')

receiptPrinter = Usb(0x04b8, 0x0202, 0)
receiptPrinter.set("center")


# When a user sends a DM, the event type will be 'message'.
# Here we'll link the message callback to the 'message' event.
@slack.RTMClient.run_on(event="message")
async def message(**payload):
    data = payload['data']
    if 'Hello world' in data['text']:
        newValue = int(float(data['text'][12:1000]))
        mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
        mydb.autocommit = True
        mycursor = mydb.cursor()
        mycursor.execute("SELECT MAX(lineID) FROM `orderLine`")
        myresult = mycursor.fetchall()
        for x in myresult:
Пример #26
0
import sys
from datetime import datetime

#  sys.argv
# [1] Código do movimento de portaria
# [2] Nome do motorista
# [3] OC ou SCM
# [4] Código da OC ou da SCM
# [5] Nome do usuário do protheus
# [6] tipo da refeição [1]café [2]almoço [3]janta

agora = datetime.now().strftime("%d/%m/%Y  |  %H:%M")

p = Usb(0x04B8, 0x0E27, 0, 0x81,
        0x02)  # Específico para impressora Epson TM-T20X
p.set(double_width=True, double_height=True)
p.control('HT')
p.text("    TICKET REFEICAO")
p.set(double_width=True, double_height=False)
p.ln()
p.ln()
p.text('       ' + sys.argv[1])
p.ln()
p.ln()
p.text('   ' + sys.argv[2].replace('_', ' '))
p.ln()
p.ln()
p.text('     ' + sys.argv[3] + ' ' + sys.argv[4])
p.ln()
p.ln()
if sys.argv[6] == '1':
Пример #27
0
import requests
import json
import time
from escpos.printer import Usb

from constants import *

p = Usb(0x471, 0x55, 0, 0x82, 0x2)
# p = Usb(0x1d6b, 0x2, 0, 0x82, 0x2)

p.set(align='center', text_type='B', width=3, height=3)
p.text('NEW ORDER' + "\n")

p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
p.cut()

p.close()

if __name__ == '__main__':
    pass
Пример #28
0
def orderProcess(queueType, awaitOrder, lidNoLid, tableLoc, MProc, updateCounter, updateInt, q):
    orderJob = get_current_job()
    orderJob.meta['lid'] = q["lid"]
    orderJob.meta['progress'] = 0
    try:
        if q['phone']:
           orderJob.meta['phone'] = q['phone']
    except:
        print("no phone#")
        orderJob.meta['phone'] = "0"
    orderJob.save_meta()
    print(orderJob)
    print(orderJob.meta)
    print(orderJob.kwargs)
    kukaDoneID = "ns=4;s=DI_KUKA_SIGNAL_DONE"
    kukaRunningID = "ns=4;s=DI_KUKA_SIGNAL_START"
    kukaWaitingID = "ns=4;s=DI_KUKA_SIGNAL_WAITING_ORDER"
    selectedQueueID = "ns=4;s=SELECTED_QUEUE"
    # print(q)
    # print(q["lid"])
    # print(q["dye"])
    # print(q["table"])
    isOPCAvailable = False
    try:
        # print("Order Processing")
        client = Client("opc.tcp://192.168.0.211:4870")  # Set OPC-UA Server
        # print("STOP")
        client.connect()
        awaitOrder = client.get_node(awaitOrder)
        while awaitOrder.get_value() is False:
            # print("HMI Not ready")
            sleep(1.0)
        sleep(6.0) # Need extra sleep to let all previous sequences clear out and become complete.
        # print("HMI is ready. Loading Values")
        M_Lid = client.get_node(lidNoLid)
        # print("Q" + q["lid"])
        if q["lid"] == "true":
            t = True
        else:
            t = False
        M_Lid.set_value(t)
        # print("Dye set" + str(dyeBool))
        M_Table = client.get_node(tableLoc)
        M_Table.set_value(int(q["table"]), VariantType.Int16)

        # print("table set" + q["table"])
        M_process = client.get_node(MProc)
        M_process.set_value(True)
        # print("process")
        awaitOrder.set_value(False)
        isOPCAvailable = True
    except OSError:
        print("OPC Server Unavailable")

    # Now monitor for status int changes
    # orderStatusCode = client.get_node()
    orderJob = get_current_job()
    orderJob.meta['progress'] = 0
    orderJob.save_meta()
    progressInt = 0
    if isOPCAvailable is False:
        asdf = 0
        while asdf < 10:
            orderJob.meta['progress'] = asdf
            # print(orderJob)
            # print(asdf)
            orderJob.save_meta()
            sleep(.05)
            asdf = asdf + 1
        orderJob.meta['progress'] = 10
        orderJob.save_meta()
    else:
        while orderJob.meta['progress'] != 10:
            client.disconnect()
            client.connect()
            countVal = client.get_node(updateCounter).get_value()
            intVal = client.get_node(updateInt).get_value()
            kukaQueue = client.get_node(selectedQueueID).get_value()
            kukaRun = client.get_node(kukaRunningID).get_value()
            kukaDone = client.get_node(kukaDoneID).get_value()
            estopstat = client.get_node("ns=4;s=M_E_Stop")
            print("Count" + str(countVal))
            print("INT COUNT" + str(intVal))
            print("kuka q" + str(kukaQueue))
            print("Kuka run" + str(kukaRun))
            print("kuka done" + str(kukaDone))
            print("quetype" + str(queueType))
            if(kukaQueue):
                print("kukaque is true")
            else:
                print("kukaqueue is false")
            if kukaRun:
                print("kukarun is true")
            else:
                print("kukarun is false")
            if queueType:
                print("qt is true")
            else:
                print("qt is false")

            if kukaQueue == queueType and (kukaRun or kukaDone ):  # IF The selected queue and working queue match, AND the kuka is in run sequence
                print("all true")
                orderJob.meta['progress'] = intVal
            else:
                orderJob.meta['progress'] = countVal
            if estopstat:
                orderJob.meta['progress'] = 30
                orderJob.save_meta()
                return
            orderJob.save_meta()
            sleep(1)

    try:
        client.disconnect()
    except (OSError, AttributeError) as e:
        print("OPC Unavailable")
    print("disconnect")
    #send sms
    try:
            name = ""
            if q['name']:
                name = q['name']
            n = phonenumbers.parse(orderJob.meta['phone'],"CA")
            if phonenumbers.is_possible_number(n):
                number = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
                print(os.getenv("TSID"))
                print(os.getenv("TAUTH"))
                client = tClient(os.getenv("TSID"), os.getenv("TAUTH"))
                message = client.messages.create(body=str("Hello "+name + "\n Your order is ready at mobile pickup :)"), from_='+16042565679', to=number)
                print(message.sid)
    except:
            print("SMS Failed to send")
    try:
        printer = Usb(0x04b8, 0x0203)
        printer.set(font='a', height=2, align='CENTER', text_type="bold")
        printer.image("cup.gif")
        try:
            printer.text(q['name']+"\n")
        except:
            printer.text("No Name\n")
        printer.set(font='a', height=1, align='center', text_type='normal')
        printer.text(str("Dye: " + str(queueType) + " || Lid: " + str(q["lid"]) + "\n"))
        printer.set(font='b', height=1, align='center', text_type="bold")
        tableprint = str(int(q["table"]))
        if int(q["table"]) == 4:
            tableprint = "Mobile Pickup"
        printer.text(str("Table " + tableprint + "\n"))
        printer.cut()
        printer.close()

    except:
        print("printer error")
Пример #29
0
def printTicket(member_id, slot, expirationDate, username, name, email, phone, storageType, description, printTime, completion):
    """ Print a storage ticket and receipt.
    """

    p = Usb(0x04b8, 0x0e15, 0)

    p.set(align='center', text_type='B', width=4, height=4)
    p.text(expirationDate)
    p.text("\n")

    p.set(align='center', width=1, height=1)
    p.text("storage expiration date\n\n")

    p.set(align='center', width=2, height=2)
    p.text("DMS Storage Ticket\n")
    p.text(str.format("Slot:\t{}\n\n", slot))
    p.text(str.format("Name:\t{}\n\n", name))

    p.set(align='left')
    p.text("Ticket required on any items left at DMS.\n")
    p.text("Place ticket in holder or on project.\n\n")

    p.set(align='left')
    p.text(str.format("User:\t{}\n", username))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Phone:\t{}\n", phone))
    p.text(str.format("Type:\t{}\n", storageType))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))
    p.text(str.format("Compl:\t{}\n", completion))

    p.text("\n\n")
    p.text("Signature: ____________________________________\n")
    p.text("By signing you agree to follow the posted rules and remove your item before the expiration date.\n")
    p.text("Failure to remove items will result in loss of\nstorage privileges.")

    p.set(align='center')
    p.text("\n")
    qrDataString = str.format("{};{};{};{}", member_id, slot, storageType, expirationDate)
    p.qr(qrDataString, 1, 6, 2)

    p.cut()

    p.set(align='center', width=2, height=2)
    p.text("DMS Storage Receipt\n\n")

    p.set(align='left', width=1, height=1)
    p.text("Keep this receipt as a reminder that you\n")
    p.text("agreed to remove your item before:\n")
    p.set(align='center', text_type='B', width=2, height=2)
    p.text(expirationDate)
    p.text("\n\n")

    p.set(align='left')
    p.text(str.format("User:\t{}\n", username))
    p.text(str.format("Name:\t{}\n", name))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Phone:\t{}\n", phone))
    p.text(str.format("Type:\t{}\n", storageType))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))
    p.text(str.format("Compl:\t{}\n", completion))
    p.cut()
Пример #30
0
from escpos.printer import Usb
from datetime import datetime
import csv

current_date = datetime.now()

with open('data.csv') as data:
    data_reader = csv.reader(data)  #use DictReader for list the used headers.
    for row in data_reader:
        paper_id = int(row[0])

p = Usb(0x0fe6, 0x811e, timeout=0)  #vendor id product id us lsusb to see

p.set(align="center", height=2)
p.text("AlSANCAK BELEDIYESI")
p.text("\nAKILLI COP TOPLAMA TERMINALI\n\n")

p.set(align="left", height=1, text_type='bold')
p.text("\nFIS NO:    ")
p.text(str(paper_id))
p.text("\nTARIH:     ")

p.text(str(current_date.strftime("%d-%m-%Y %H:%M")))

p.text("\n\nCOP CINSI\n\n")
p.text("METAL:       ")
p.text("2\n")
p.text("PLASTIK:     ")
p.text("3\n")
p.text("CAM:         ")
p.text("5\n")
Пример #31
0
def impr(data = []):
    """
    Data = id de proyectos votados
    :param data:
    :return:
    """
    p = Usb(0x04b8, 0x0e15, 0, )
    # f = open("to_save", 'r+')
    # lines = f.readlines()[0]
    # data = ast.literal_eval(lines)
    p.image("{}functions/cabecera.jpg".format(path_proyecto))
    p.set(font='a', height=1, align='center')
    p.codepage = 'cp850'
    # p.charcode("MULTILINGUAL")
    # print(p.codepage)
    try:
        p.text('Presupuestos Participativos de Inversiones 2018\n')
        p.text('- Recibo informativo - \n')

        p.text('----------------------------------- \n')
        p.set(font='a', height=2, align='center')
        # date = datetime.now()
        date = datetime.now() + timedelta(hours=2)
        p.text('Votación realizada: \n {} \n \n'.format(date.strftime("%Y-%m-%d %H:%M:%S")))
        p.set(font='a', height=2, align='center')
        p.text('Proyectos elegidos: \n \n')
        p.set(font='a', height=1, align='center')
        #propuestas
        contMax = 0
        for i in data:
            e = propuestas.search_name_by_id(i)
            if e is None:
                print("Id de proyecto {} no valido".format(i))

            else:
                title, price = e
                contMax = contMax + int(price)
                price = format_price(price)
                p.text('{} - {} e \n\n'.format(title, price))

        p.set(font='a', height=2, align='center')
        p.text('\n Inversión total votada: ')
        p.text('{} e \n'.format(format_price(contMax)))
        p.set(font='a', height=1, align='center')
        p.text('\n \n Gracias por su participación \n')
        p.text('----------------------------------- \n')
        p.set(font='a', height=1, align='center')
        p.text(
            'Sistema presencial de votación electrónica \n')
        p.text("Evotebox \n")
        p.image("{}functions/gente.png".format(path_proyecto))
        p.cut()
        p.close()
    except:
        # print(traceback.format_exc())
        p.cut()
        p.close()