示例#1
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()
示例#2
0
def print_trans():
  if platform.system() == 'Windows':
    process = subprocess.Popen(['php', 'printWindows.php'] + sys.argv[1:], stdout=subprocess.PIPE).communicate()[0]
    return process
  else:
    invoice = str(request.data.get('invoice', ''))
    conn = mysql.connect()
    cursor = conn.cursor()
    cursor.callproc('sp_getprint', (invoice,))
    data = cursor.fetchall()

    conn2 = mysql.connect()
    cursor2 = conn2.cursor()
    cursor2.callproc('sp_gettoko')
    toko = cursor2.fetchall()

    p = Usb(0x0416, 0x5011, 0)

    for item in toko:
      p.text(str(item[1]) + "\n")
      p.text(str(item[2]) + "\n")
      p.text("===============================\n")

    for item in data:
        p.text(str(item[0]) + " " + str(item[1]) + " " + str(item[2]) + "\n")

    p.cut()
    p.cashdraw(2)
    return "Print success"
示例#3
0
def imprimir_ticket(x, y):
    c = 0
    print "Imprimiendo ----><"
    try:
        p = Usb(0x04b8, 0x0202)
        while (not p):
            print "gettin access to printer"
            c = c + 1
            time.sleep(1)
            if (c == 5):
                print "non se puede conectar a Impresora..."
                print "Saliendo sin Imprimir!!!!"
                break
    except:
        print "Error con impresora!!!"
    try:
        p.text("=====================================\n")
        p.text("  ---------- SHOPPING NORTE ---------- \n")
        p.text("  ---------- Parking Ticket ---------- \n")
        p.text("===================================== \n")
        p.text("Matricula:        " + x + "          \n")
        p.text("Fecha de ingreso: " + y + "\n")
        p.text("       Gracias por su preferencia!!!  \n")
        p.text("=====================================\n")
        p.text("========== La Paz - Bolivia  ========\n")
        p.text("\n")
        p.cut()
    except:
        print "no se pudo imprimir"
示例#4
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()
示例#5
0
文件: reapair.py 项目: Foaly/ReapAir
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()
示例#6
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()
示例#7
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()
示例#8
0
def print_text(text):
    '''
    Prints the given text and cuts it. Returns True on success
    '''
    p = Usb(product_id, vendor_id, 2)
    curtime = time.strftime("%H:%M, %d/%m/%Y")
    to_print = curtime + "\n" + text
    p.text(to_print)
    p.text("\n")
    p.cut()
示例#9
0
def printTicketFunc(expirationDate, name, email, type, description, printTime):
    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\n")
    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("Name:\t{}\n", name))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Type:\t{}\n", type))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))

    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("{};{};{};{}", name, email, type, printTime)
    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("Name:\t{}\n", name))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Type:\t{}\n", type))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))
    p.cut()
def printchart():

    df = pd.read_csv(
        'http://www.cryptodatadownload.com/cdd/gemini_BTCUSD_1hr.csv',
        skiprows=1)
    df = df.head(50)

    fig = go.Figure(data=[
        go.Candlestick(x=df['Date'],
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'])
    ])

    fig.update_layout(xaxis_rangeslider_visible=False, width=580, height=400)

    fig.write_image("fig1.png")
    #fig.show()

    WHITE = 1
    BLACK = 0

    p = Usb(0x0483, 0x5720, 0)
    recipt = Image.new('1', (580, 500), 1)

    x1 = 0
    y1 = 0

    im2 = Image.open('btclogo.png')
    recipt.paste(im2)

    x1 = 0
    y1 = 149

    im1 = Image.open('fig1.png')
    recipt.paste(im1, (x1, y1))

    #draw = ImageDraw.Draw(recipt)

    #UbuntuFont = ImageFont.truetype("fonts/Ubuntu-MediumItalic.ttf")

    #msg='Bitcoin Chart BTCUSD'
    #draw.text((0, 410), msg, fill=BLACK, font=UbuntuFont)

    #LOCAL SAVE
    #recipt.save("tmp.png")
    #os.system("open tmp.png")

    p.image(recipt)

    #p.image('fig1.png', high_density_vertical=True, high_density_horizontal=True, impl=u'bitImageRaster', fragment_height=960)

    p.cut()
    '''
示例#11
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()
示例#12
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()
示例#13
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")
示例#14
0
 def post_add(self, item):
     stroka = str()
     len_id = len(str(item.id))
     const_len = 9
     while(len_id < const_len):
         stroka += '0'
         len_id += 1
     stroka += str(item.id)
     p = Usb(0x1d90,0x2060,0,0x81,0x02)
     p.barcode(stroka,'CODE39',250,3,'','')
     p.cut()
     p.barcode(stroka,'CODE39',250,3,'','')
     p.cut()
示例#15
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()
示例#16
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()
示例#17
0
def printer_print(code):
    from escpos.printer import Usb
    p = Usb(int(get_printer_id()[0], 16), int(get_printer_id()[1], 16), 0)
    if p.paper_status() == 2:
        text = 'Discount Code:\n\t{}\n'.format(code)
        p.text(text)
        p.barcode('1234567898765', 'EAN13', 64, 2, '', '')
        p.cut()
    elif p.paper_status() == 1:
        print('Paper running out soon!')
        # TODO: inform the manager immediately about the paper issue
        pass
    else:
        # TODO: show warning on screen that the machine is temporarily not able to print out barcode for non-app user,
        #  app users can still scan the barcode on the screen to obtain the voucher code
        pass
示例#18
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()
示例#19
0
def print_bar(name):
    width = 580
    height = 100

    image = Image.new('1', (width, height), 255)
    draw = ImageDraw.Draw(image)
    #font1 = ImageFont.truetype('clamp-1m-w4-regular.ttf', 50, encoding='unic')
    #draw.text((0, 0), "Barcode" + " ", font=font1, fill=0)
    font2 = ImageFont.truetype('Code39Barcode.ttf', 55)
    draw.text((0, 00), "*" + name + "*" + " ", font=font2, fill=0)

    p = Usb(0x0416, 0x5011, 0, 0x81, 0x03)
    p.text(" " + name + "\n")
    p.image(image)
    p.qr(name, size=6)
    #p.barcode("1324354", "CODE39")
    #p.barcode("{B012ABCDabcd", "CODE39", function_type="B")
    p.cut()
    return ''
示例#20
0
class ReceiptPrinter:
    def __init__(self,
                 id_vendor=0x0416,
                 id_product=0x5011,
                 in_ep=0x81,
                 out_ep=0x03):
        self._printer = Usb(id_vendor, id_product, in_ep=in_ep, out_ep=out_ep)

    def print(self, img):
        self._printer.image(img)
        self._printer.cut()

    def print_data(self, data):
        img = Receipt.from_data(data)
        self.print(img)

    def print_stream(self, stream):
        img = Receipt.from_stream(stream)
        self.print(img)
示例#21
0
def printer_output(result, name):
    MAX_WIDTH = 600 # The size of the printer
    img = Image.open(os.path.join('images', f'{result}.jpg'))
    w, h = img.size
    # Resize width to MAX_WIDTH
    scale = MAX_WIDTH / w
    new_w, new_h = int(scale*w), int(scale*h)
    new_img = img.resize((new_w, new_h))
    # Add text (user name)
    font = ImageFont.truetype('./Microsoft-JhengHei.ttf', 35)
    d = ImageDraw.Draw(new_img)
    text_w, text_h = d.textsize(name, font=font)
    d.text((335-text_w/2,480), name, font=font, fill=(0, 0, 0))

    try:
        p = Usb(0x1fc9, 0x2016)
        p.image(new_img)
        p.cut()
    except Exception as e:
        raise e
示例#22
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()
示例#23
0
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")
p.text("KARTON:      ")
p.text("9\n\n")

p.text("PUAN:        ")
p.text("55")
p.cut()

paper_id += 1
with open('data.csv', 'w') as data:
    data_writer = csv.writer(data)
    data_writer.writerow({paper_id})
    print(paper_id)
示例#24
0
    printer.image(image)


if __name__ == '__main__':

    # Some Text
    ptTitle = u'Test Title'
    ptText = u'Test Text'
    ptQR = u'This is my Alipay QRCode'

    # Print Something
    PrintAlign(1)
    PrintTime()
    PrintText(ptTitle, inputSize=36, inputBold=True)
    PrintSpace(20)

    PrintAlign(0)
    PrintText(ptText, inputBorder=2)
    PrintSpace(20)

    PrintAlign(1)
    PrintText(ptQR, inputSize=20)
    PrintImage("http://brainexplode.com/money.jpg")
    #printer.qr('http://brainexplode.com/me.html', ec=2, size=8)

    PrintSpace(20)
    PrintLine(1)

    printer.cut()
    printer.close()
示例#25
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")
示例#26
0
class Printer():
    """ Loads a printer according to the model supplied (explicit list of support)
        and provides common functions
    """
    def __init__(self, name: str = "", model: str = "", **kwargs):

        if not name:
            # Forces a unique printer name
            name = f"printer-{id(self)}"
        self.name = name

        if model:
            self.printer_spec = PRINTER_MAP.get(str(model), dict())
        else:
            self.printer_spec = PRINTER_MAP.get("default")

        self.model = self.printer_spec.get('model', 'unknown')

        valid_kwargs = getfullargspec(Usb)
        # ['self', 'idVendor', 'idProduct', 'timeout', 'in_ep', 'out_ep']

        # Look for kwargs passed that match a kwarg for Usb() and override
        for k, v in kwargs:
            if k in valid_kwargs:
                self.printer_spec["config"][k] = kwargs.pop(k, None)

        self.inputs = locals()

        config = self.printer_spec['config']
        self.printer = Usb(**config)

        # TODO: Add logic that verifies the printer is working

    def ln(self, count=1):
        """ feeds n lines to print buffer
            replicates Escpos().ln() in newer version (>=3.0)
            https://github.com/python-escpos/python-escpos/blob/f9ce77705757dcd3a3946569d02810ae7e122e88/src/escpos/escpos.py#L531
        """
        if count < 0:
            count = 0
        if count == 0:
            return False
        return self.printer.text('\n' * count)

    def text(self, text):
        """ Pass through to Escpos().text()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L424
        """
        self.printer.text(text)
        return True

    def cut(self, mode="PART"):
        """ Pass through to Escpos().cut()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L597
        """
        return self.printer.cut(mode)

    # TODO: Make this better
    def barcode(self, *args, **kwargs):
        """ Pass through to Escpos().barcode()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L295
        """
        return self.printer.barcode(*args, **kwargs)

    # TODO: Make this better
    def qr(self, *args, **kwargs):
        """ Pass through to Escpos().qr()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L134
        """
        return self.printer.qr(*args, **kwargs)
                    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:
    if entry_list.index(item)%2 == 0 and entry_list.index(item)+1 <len(entry_list):
        try:
            Printer.text('{:3s} {:>5s} {:>23s}'.format('[ ]', item, entry_list[entry_list.index(item)+1]) + "\n")
        except UnicodeDecodeError:
            print "Error by Item:" + item
Printer.cut()
示例#28
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')
示例#29
0
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':
    p.text('         ' + "Cafe")
elif sys.argv[6] == '2':
    p.text('          ' + "Almoco")
elif sys.argv[6] == '3':
    p.text('         ' + "Janta")
p.ln()
p.ln()
p.text('   ' + sys.argv[5].replace('_', ' '))
p.ln()
p.text('  ' + agora)
p.ln()
p.ln()
p.text("_______________________")
p.ln()
p.cut(mode='FULL')
示例#30
0
文件: print.py 项目: ev-devs/kprint
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()
示例#31
0
                                   Attributes=['ALL'])

    return response['FaceDetails']


try:
    while FLAG:
        os.system('cls' if os.name == 'nt' else 'clear')
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            line = raw_input()
            break
        if GPIO.input(SW_PIN) == GPIO.HIGH:
            print("Caught")
            os.system('fswebcam -S 10 ' + IMGFACE)
            usb = Usb(0x067b, 0x2303, 0, out_ep=0x2)
            usb.cut()
            usb.image(IMGFACE)
            with open(IMGFACE, 'rb') as source_image:
                source_bytes = source_image.read()

            time.sleep(1)
            for face in detect_faces(source_bytes):
                usb.text("Face ({0:.2f}%)\n".format(face['Confidence']))

            for emotion in face['Emotions']:
                usb.text("  {Type} : {Confidence}% \n".format(**emotion))
                emotion_type = emotion['Type']
                idx = float("{0:.2f}".format(emotion['Confidence']))

                if emotion_type == "HAPPY" and idx > 70:
                    usb.image(IMGHAPPY)