def main(): names = [ '神社 太郎', '神社 次郎', '神社 三郎', ] tadashi = 'xx神社祭典運営費拠出金' for name in names: create_img(name, tadashi) sleep(0.5) p = Usb(0x0416, 0x5011, out_ep=3) p.image('output.png') p.text('\n\n\n') print('Please hit any key') input() create_img(name, tadashi, copy=' <控>') sleep(0.5) p = Usb(0x0416, 0x5011, out_ep=3) p.image('output.png') p.text('\n\n\n') print('Please hit any key') input()
class Printer(): def __init__(self, code=(0x0416, 0x5011, 0x81, 0x03)): self.code = code try: self.usb = Usb(*self.code) except Exception as e: print(e) @module_method def image(self, image_path): self.usb.image(image_path, impl='bitImageColumn') @module_method def text(self, text): self.usb.text(text) @module_method def html(self, html_str): image_file = renderer.html_to_image(html_str) self.image(image_file) @module_method def markdown(self, text): image_file = renderer.markdown_to_image(text) self.image(image_file) @module_method def providers(self, *providers): html_str = '' for p in providers: html_str += p.render() self.html(html_str)
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()
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()
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()
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() '''
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()
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()
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")
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()
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()
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()
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)
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 ''
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
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()
def main(): # Demo try: p = Usb(0x0416, 0x5011) except usb.core.USBError as e: if e.errno == 13: print("Printing permission is required. (are you root?)") subprocess.call(['sudo', '/usr/bin/env', 'python3', *sys.argv]) quit(1) else: print( "Unknown Error about has catched during handling with USB Device. Program will closed.\n==========================" ) raise e tt = softunicode(350) tt.changeFontTTF('neodgm.ttf', size=32) try: while True: p.image(tt.text(input()), impl=u'bitImageColumn') finally: p.text("\n\n\n") p.close()
def svg_to_printer(svg): #config printer p = Usb(0x4b43, 0x3538, 0, 0xB2, 0x02) # lsus # lsusb -vvv -d 4b43:3538"b # sudo usermod -a -G dialout user # sudo usermod -a -G tty user # sudo usermod -a -G lp user # ls -la /dev/usb/ # escape svg tofile("svg_to_print1_debug.svg", svg) svg = svg.decode('utf-8').encode( 'ascii' ) # todo: problem with special char are used, find othern way to do that. tofile("svg_to_print2_debug.svg", svg) # image = 384 x 175 -- print area = 384 x 154 pngfile = StringIO() #temp file pngbuffer = svg2png(bytestring=svg, write_to=pngfile) #SVG to PNG #pngbuffer = svg2png(bytestring=svg, write_to="label.png") #SVG to PNG #debug p.image(pngfile) #PNG to printer return render_template('edit.html')
class ESCpos(DummyPrinter): MAX_PRINTER_DOTS_PER_LINE = 384 TYPE = "ESCpos" _dev = None # USB specific constant definitions USB_VENDOR_ID = 0x0416 USB_DEVICE_ID = 0x5011 # Zjiang POS Thermal Printer Mini 58mm USB - https://www.aliexpress.com/item/1000006163834.html def __init__(self, logger): DummyPrinter.__init__(self, logger) self.ESCposPrinter = ESCposUSBInterface(self.USB_VENDOR_ID, self.USB_DEVICE_ID) def print(self, input_buffer, opts): printjob = DummyPrinter.print(self, input_buffer, opts) if opts.mode == PRINT_MODE_TXT: self._print_text(printjob, opts) else: self._print_image(printjob, opts) def _print_image(self, img, opts): """Take the PILlow image, and convert to ESC format, and print""" # I am a mono printer, I INSIST this is a mono image... img = img.convert("1") tmpfile = opts.args.temppath + os.path.sep + int( round(time.time() * 1000)).__str__() + ".png" img.save(tmpfile) self.ESCposPrinter.image(tmpfile, True, True, u'bitImageColumn') os.remove(tmpfile)
from escpos.printer import Usb from PIL import * import requests, json import time printer = Usb(0x0416, 0x5011) while True: r = requests.get('http://127.0.0.1:8080/api/print/') if r.status_code == 200: for visitante in r.json(): print(visitante) printer.text('\n\n') printer.image('head.gif') printer.text('Nome: {}\n'.format(visitante['nome'][0:20])) printer.text('Telefone: {}\n'.format(visitante['telefone'])) printer.text('CPF: {}.xxx.xxx.xxx-xx \n'.format( visitante['documento'][0:3])) if visitante['tipo'] == 1: printer.text('------------------------------\n') printer.text('-----------LOJISTA------------\n') printer.text('------------------------------\n') printer.image('footer.gif') printer.text('------------------------------\n') printer.text('\n\n') rput = requests.put('http://127.0.0.1:8080/api/print/{}/'.format( visitante['id']), data=json.dumps({'impresso': True}), headers={'Content-Type': 'application/json'}) print(rput.text) time.sleep(3) print('loop')
from escpos.printer import Usb, Dummy, Serial import os import hashlib #Print System usb id information os.system("lsusb") print("\n\n") #Get user usbid ''' vid = input("\nPlease input VendorID (e.g.:0x21a1):") vid = int(vid,16) pid = input("\nPlease input ProductID (e.g.:0x2123):") pid = int(pid,16) oep = input("\nPlease input ENDPOINT:") oep = int(oep,16) print("\nThe USB VendorID is ["+str(vid)+"] ProductID is ["+str(pid)+"]") ''' i = 0 p = Usb(0x0483, 0x070b, 0, out_ep=0x2) p.text("HELLO WORLD! I'M PRINTER!\n\n") p.image("timg.jpg") while True: pstr = str(hashlib.md5(i + 123).hexdigest()) p.text(pstr) i = i + 1
PDFPageCountError, PDFSyntaxError ) print('drag the file you wanna print here.') image_path = input().strip() format = image_path.split('.')[-1] if format == 'pdf': images = convert_from_path(image_path) img = images[0].convert("RGBA") elif [format == 'jpeg'] or [format == 'jpg'] or [format == 'png']: img = PIL.Image.open(image_path).convert("RGBA") img.load() background = PIL.Image.new("RGB", img.size, (255, 255, 255)) background.paste(img, mask=img.split()[3]) background.save("out.jpg","JPEG",quality=95) currentWidth = background.width currentHeight = background.height ratio = currentHeight/currentWidth width=384 height = int(width*ratio) img = background.resize((width,height)) img_name = datetime.datetime.today().strftime("%Y%m%d%H%M%S") + '.jpg' img.save(img_name) from escpos.printer import Usb p = Usb(0x0416, 0x5011, out_ep=3) p.image(img_name) p.text('\n\n\n\n\n\n')
"?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) printer.text(' ') printer.text(deg) printer.text(' ') printer.text('\n') printer.text('Sky: ' + cond) printer.text('\n') printer.text('\n') # Print forecast
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) if emotion_type == "SAD" and idx > 10:
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()
p.device.write(p.out_ep, HW_INIT, 1000) i() p.device.reset() i() p.device.reset() i() p.device.reset() i() #p.device.reset() p.device.reset() p.device.reset() #p.device.reset() #p.device.reset() #p.device.reset() i() p.device.write(p.out_ep, HW_INIT, 1000) #p.device.write(p.out_ep, HW_SELECT, 1000) #p.device.write(p.out_ep, HW_RESET, 1000) i() #p.image("/tmp/blank.jpg", impl='bitImageColumn') p.image("/tmp/blank.jpg", fragment_height=2500, impl='graphics', high_density_vertical=False, high_density_horizontal=False) i() #p.cut() i()
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')
# sudo pip3 install python-escpos --pre import sys from escpos.printer import Usb if __name__ == '__main__': p = Usb(0x0416, 0x5011) p.text('micavibe.com/mood\n\n') p.image('tomicavibe_mood.png') p.text('\n\n\n\n') # from escpos.connections import getUSBPrinter # # # Bus 020 Device 008: # # ID 0416:5011 Winbond Electronics Corp. POS58 USB Printer Serial: Printer # printer = getUSBPrinter()(idVendor=0x0416, # idProduct=0x5011) # Create the printer object with the connection params # # printer.text("Hello World") # printer.lf() #
from escpos.printer import Usb from pathlib import Path image = Path("/tamamo-no-mae/me-cloudy.png") printer = Usb(0x0416, 0x5011, 0, profile="ZJ-5870") printer.image(image) printer.cut() # with printer() as that: # that.write('Hello, world!\n\n') # # 000000000111111111122222222223 # # 123456789012345678901234567890 # that.write('Soluta sed voluptatem ut\n') # that.write('facere aut. Modi placeat et\n') # that.write('eius voluptate sint ut.\n') # that.write('Facilis minima ex quia quia\n') # that.write('consectetur ex ipsa. Neque et\n') # that.write('voluptatem ipsa enim error\n') # that.write('rthatrehenderit ex dolore.\n') # that.write('Cupiditate ad voluptatem nisi.\n\n\n\n') # ZJ-5870
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")
#!/usr/bin/python3 import time from escpos.printer import Usb from PIL import Image, ImageFont, ImageDraw WHITE = 1 BLACK = 0 p = Usb(0x0483, 0x5720, 0) #p.qr('LNURL1DP68GURN8GHJ7MRWW4EXCTNRDAKJ7ENPW43K2AP0VAJKUETJV96X7U30V93HGTNSDPCR76TY85ERYDNY8Y6NYCEDX3SNXDFDXSCKXWPD8P3KGVFDV4NX2C3KXGMR2DRRV9JQ28SW6J',ec=0,size=12) p.image('/home/afonsom/Downloads/NyanCatLong.png') #image = Image.new('1', (590,100), BLACK) #draw = ImageDraw.Draw(image) #draw.rectangle((0, 0, 599, 99), fill=WHITE, outline=BLACK) #draw.text((20, 10), 'Welcome to the', fill=BLACK) #draw.text((10, 20), 'LightningATM', fill=BLACK) #draw.text((7, 75), '- please insert coins -', fill=BLACK) p.image(image) p.cut() #time.sleep(2) #p.cashdraw(2)