def printDesglose(self, p, fecha, lineas): if type(fecha) is datetime: fecha = fecha.strftime("%d/%m/%Y %H:%M:%S") else: fecha = datetime.strptime(fecha, "%Y-%m-%d %H:%M:%S.%f") fecha = fecha.strftime("%d/%m/%Y %H:%M:%S") printer = Network(ip_caja, timeout=10) with EscposIO(printer) as p: p.writelines("Cierre de caja", align='center', width=2, height=2) p.writelines(fecha, align='center', width=2, height=2) p.writelines("------------------------------------------", align='center') p.writelines("") for linea in lineas: can = linea["can"] texto_tipo = linea["texto_tipo"] tipo = linea["tipo"] p.writelines("Retirar {0: >5} {1} de {2}".format( can, texto_tipo, tipo), height=2, align='center') p.writelines("") p.writelines("")
def connect_to_printer(self): NETWORK_PRINTER_IP = config['twitter_printer_ip'] if self.printer: self.printer.close() try: self.printer = Network(NETWORK_PRINTER_IP) except: _logger.error("Can not get printer with IP: %s" % NETWORK_PRINTER_IP) self.printer = False
class Printr: def __init__(self, bot, config): self.bot = bot self.config = config self.printer = self.config.get("printer") self.p = None @onload def onload(self): self.p = Network(self.printer) print("printer loaded") @unload def unload(self): self.p = None @command("print") def printr(self, msg): self.p.text(msg.text) self.p.cut() return msg.reply(text="Printed!")
def imprimirUrgente(self, camarero, mesa, hora, lineas): try: if self.tipo == "Network": printer = Network(self.ip_caja, timeout=1) if self.tipo == "Usb": printer = Usb(*self.usb) if self.tipo == "File": printer = File(self.url) with EscposIO(printer) as p: p.printer.codepage = 'cp858' p.printer._raw(escpos.CHARCODE_PC852) p.printer.set(align='center') p.writelines("") p.writelines('URGENTE!!', height=2, width=2, font='a', align='center') p.writelines('------------------------------------------', align='center') p.writelines('HORA: %s' % hora, height=2, width=2, font='b', align='center') p.writelines("Mesa: %s" % mesa, height=2, width=2, font='a', align='center') p.writelines(camarero, height=2, width=2, font='a', align='center') p.writelines('------------------------------------------', align='center') p.writelines("") for ln in lineas: p.writelines("{0: >3} {1: <25} {2:0.2f}".format( ln['can'], ln['nombre'], float(ln["precio"])), height=2, align='center') p.writelines("") p.writelines("") except Exception as e: print("[ERROR ] %s" % e)
def abrir_cajon(self, *args): try: if self.tipo == "Network": printer = Network(self.ip_caja, timeout=1) if self.tipo == "Usb": printer = Usb(*self.usb) if self.tipo == "File": printer = File(self.url) printer.cashdraw(2) except Exception as e: print("[ERROR ] %s" % e)
def printDesglose(self, fecha, lineas): if type(fecha) is datetime: fecha = fecha.strftime("%d/%m/%Y %H:%M:%S") else: fecha = datetime.strptime(fecha, "%Y-%m-%d %H:%M:%S.%f") fecha = fecha.strftime("%d/%m/%Y %H:%M:%S") try: if self.tipo == "Network": printer = Network(self.ip_caja, timeout=1) if self.tipo == "Usb": printer = Usb(*self.usb) if self.tipo == "File": printer = File(self.url) with EscposIO(printer) as p: p.printer.codepage = 'cp858' p.printer._raw(escpos.CHARCODE_PC852) p.writelines("Cierre de caja", align='center', width=2, height=2) p.writelines(fecha, align='center', width=2, height=2) p.writelines("------------------------------------------", align='center') p.writelines("") for linea in lineas: can = linea["can"] texto_tipo = linea["texto_tipo"] tipo = linea["tipo"] titulo = linea["titulo"] p.writelines("{3} {0: >5} {1: <3} de {2:6.2f} €".format( can, texto_tipo, tipo, titulo), height=2, align='center') p.writelines("") p.writelines("") except Exception as e: print("[ERROR ] %s" % e)
def checkConnection(): try: ipPrintert = request.args.get('ip', False) if ipPrintert == '' or ipPrintert == False: return make_response( jsonify(message='Required query ip', success=False), 422) thermal = Network(ipPrintert, timeout=5) return make_response( jsonify(success=True, message='Connection Successfull Thermal ' + ipPrintert), 200) except Exception as e: message = str(e) return make_response( jsonify(success=False, message='Connection Failed Thermal ' + ipPrintert, detail=message), 422)
def printEscpos(): if request.method == "POST": # get json data from request requestBody = request.get_json() ipPrintert = request.args.get('ip', False) fileString = requestBody.get('image', False) # check required body request if fileString == '' or fileString == False: return make_response( jsonify(message='Required image', success=False), 422) if ipPrintert == '' or ipPrintert == False: return make_response( jsonify(message='Required ip in query', success=False), 422) try: # service convert base64 to image imgdata = service.base64ToImage(fileString) if imgdata == '' or imgdata == False: return make_response( jsonify(message='Convert base64 to image error', success=False), 422) # print to thermal escpos printer = Network(host=ipPrintert, port=9100, timeout=30) printer.image(imgdata) printer.cut() # printer.cashdraw('pin') return make_response( jsonify(success=True, message='Success print to thermal ' + ipPrintert), 200) except Exception as e: message = str(e) logging.exception(message) return make_response( jsonify(message='Failed print to thermal ' + ipPrintert, success=False, detail=message), 500)
# Function to print the result from escpos.printer import Usb from escpos.printer import Network from escpos import exceptions as escposExceptions # Initialize the printer # USB try: printer = Usb(0x0483, 0x5743, 0) except escposExceptions.USBNotFoundError: print("Stampante USB non rilevata") # NETWORK try: ip_address = '192.168.1.100' printer = Network(ip_address) except OSError: # To change print("Stampante di rete non rilevata") exit() printer.codepage = 'CP858' def printAll(total_item, real_item_list, tmp_item_list, total_tk): # print(printer.paper_status()) printer.set(align='center', height=2) printer.text("LAVANDERIA VALDELSA\n") printer.text("Via Roma 22/24\n") printer.text("53034 - Colle di Val d'Elsa(SI)\n") printer.text("0577 920703\n\n") printer.set(width=2) printer.text("________________________\n")
import pyzmail import urllib3 import pprint import requests from imapclient import IMAPClient import re from bs4 import BeautifulSoup from escpos.printer import Network #imgkit options options = {'width': '300'} ##defind kitchen printer settings kitchen = Network("192.168.16.80") #Printer IP Address ##define Mail Login HOST = '' USERNAME = '' PASSWORD = '' #Define wp login details wp_login = '' username = '' password = '' #Functiontime Baby def getmail(): server = IMAPClient(HOST, use_uid=True, ssl=True) server.login(USERNAME, PASSWORD)
def onload(self): self.p = Network(self.printer) print("printer loaded")
# -*- coding: cp1254 -*- from escpos.printer import Network p = Network("192.168.2.223") p.image('./images/bishop.png') p.text("MUTFAK\n") p.text(chr(27)) p.text(chr(45)) p.text(chr(50)) p.text(u'DONDURUCU\n') p.text(chr(27)) p.text(chr(33)) p.text(chr(17)) p.text('NEN 2016 \n') p.barcode("3057", "CODE39",80,3,"BELOW", "A") p.text('\n') p.barcode("3058", "CODE39",80,3) p.cut()
def post(self, request, id): booking = get_object_or_404(Booking, pk=id) if 'booking_delete' in request.POST: booking.delete() return HttpResponseRedirect('/booking/') else: editBookForm = EditBookingForm(request.POST, instance=booking) if editBookForm.is_valid(): booking = editBookForm.save(commit=False) for ns in booking.services.all(): booking.services.remove(ns) for ns in editBookForm.cleaned_data["services"]: service = AddService.objects.get(name=ns) booking.services.add(service) for ns in booking.includes.all(): booking.includes.remove(ns) for ns in editBookForm.cleaned_data["includes"]: includeservice = IncludeService.objects.get(name=ns) booking.includes.add(includeservice) booking.save() if 'booking_activate' in request.POST: setting = Setting.objects.first() if setting.is_print: printer = Network(setting.network) listSessions = list() simpleCash, addingCash, simpleCard, addingCard = 0, 0, 0, 0 if booking.dep_cash > 0: simpleCash = booking.dep_cash // booking.persons addingCash = booking.dep_cash % booking.persons if booking.dep_card > 0: simpleCard = booking.dep_card // booking.persons addingCard = booking.dep_card % booking.persons prevCompany = Company.objects.filter( date__gte=date.today().replace(day=1)).last() prevCompanyID = 0 if prevCompany is None else prevCompany.CID room = booking.room tariff = booking.tariff discount = booking.discountB countSessions = booking.persons counter = countSessions countOwners = tariff.free if tariff.type == "fp" else discount.free if discount is not None else 0 company = Company.objects.create(CID=prevCompanyID + 1, count=countSessions, tariff=tariff, discount=discount) today = datetime.now(TZL) todayMonth = str( today.month) if today.month >= 10 else "0" + str( today.month) todayDay = str( today.day) if today.day >= 10 else "0" + str(today.day) todayCID = str( company.CID) if company.CID >= 100 else "0" + str( company.CID) if company.CID >= 10 else "00" + str( company.CID) partSID = str( today.year) + todayMonth + todayDay + todayCID while counter > 0: todaySID = str( counter) if counter >= 10 else "0" + str(counter) session = Session.objects.create(SID=partSID + str(todaySID), room=room, company=company) if countOwners > 0: session.owner = True session.save() countOwners -= 1 if counter == countSessions: session.text = booking.text session.dep_cash = simpleCash + addingCash session.dep_card = simpleCard + addingCard for us in booking.services.all(): useservice = UseService.objects.create(add=us) useservice.save() session.services.add(useservice) for ns in booking.includes.all(): session.includes.add(ns) else: session.dep_cash = simpleCash session.dep_card = simpleCard session.save() if setting.is_print: listSessions.append(session) counter -= 1 booking.delete() if setting.is_print: printEnteredTickets(printer, listSessions) return HttpResponseRedirect('/session/') else: return HttpResponseRedirect('/booking/') else: context = self.getcontext(editBookForm) return render(request, self.template_name, context)
def abrir_cajon(self, *args): try: printer = Network(ip_caja, timeout=10) printer.cashdraw(2) except Exception as e: print("[ERROR ] %s" % e)
def print_ticket(trx_data, gate): try: p = Network(gate['printer_ip_address']) except Exception as e: logging.error(gate['name'] + ' : Failed to print ticket ' + trx_data['barcode_number'] + ' ' + str(e)) send_notification( gate, 'Pengunjung di ' + gate['name'] + ' gagal print tiket. Informasikan nomor barcode kepada pengunjung. ' + trx_data['barcode_number']) return try: p.set(align='center') p.text("TIKET PARKIR\n") p.set(height=2, align='center') p.text(LOCATION['name'] + "\n\n") p.set(align='left') p.text('GATE'.ljust(10) + ' : ' + gate['name'] + "/" + gate['vehicle_type'] + "\n") p.text('TANGGAL'.ljust(10) + ' : ' + datetime.datetime.strptime( trx_data['time_in'][:10], '%Y-%m-%d').strftime('%d %b %Y') + "\n") p.text('JAM'.ljust(10) + ' : ' + trx_data['time_in'][11:] + "\n\n") p.set(align='center') p.barcode(trx_data['barcode_number'], 'CODE39', function_type='A', height=100, width=4, pos='BELOW', align_ct=True) p.text("\n") p.text(LOCATION['additional_info_ticket']) p.cut() except Exception as e: logging.error(gate['name'] + ' : Failed to print ticket ' + trx_data['barcode_number'] + ' ' + str(e)) send_notification( gate, 'Pengunjung di ' + gate['name'] + ' gagal print tiket. Informasikan nomor barcode kepada pengunjung. ' + trx_data['barcode_number']) return logging.info(gate['name'] + ' : Ticket printed ' + trx_data['barcode_number'])
def abrir_cajon(self, *args): try: printer = Network(ip_caja, timeout=10) printer.cashdraw(2) except: print("Impresora no conectada")
def imprimirPreTicket(self, camarero, numcopias, fecha, mesa, lineas, total): if type(fecha) is datetime: fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") else: fecha = datetime.strptime(fecha, "%Y-%m-%d %H:%M:%S.%f") fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") try: if self.tipo == "Network": printer = Network(self.ip_caja, timeout=1) if self.tipo == "Usb": printer = Usb(*self.usb) if self.tipo == "File": printer = File(self.url) with EscposIO(printer) as p: p.printer.codepage = 'cp858' p.printer._raw(escpos.CHARCODE_PC852) p.printer.set(align='center') p.writelines('PRETICKET', font='a', height=2, align='center') p.writelines('') p.writelines('------------------------------------------', align='center') p.writelines('FECHA', height=2, width=2, font='a', align='center') p.writelines(fecha, height=2, width=1, font='b', align='center') p.writelines("Num copias: %d" % numcopias, font='a', align='center') p.writelines("Mesa: %s" % mesa, font='a', align='center') p.writelines('------------------------------------------', align='center') for ln in lineas: p.writelines( "{0: >3} {1: <20} {2:5.2f} € {3:6.2f} €".format( ln['can'], ln['nombre'], float(ln['precio']), float(ln['totallinea'])), align='center', font="a") p.writelines("") p.writelines("Total: {0:0.2f} €".format(float(total)), align='right', height=2) p.writelines("") p.writelines("No olvide pedir su ticket", text_type='bold', height=2, align='center') p.writelines(camarero, text_type='bold', font='a', align='center') p.writelines("") p.writelines("") except Exception as e: print("[ERROR ] %s" % e)
def imprimirTicket(self, p, num, lineas, fecha, total, efectivo, cambio, cl=None): if type(fecha) is datetime: fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") else: fecha = datetime.strptime(fecha.replace("T", " "), "%Y-%m-%d %H:%M:%S.%f") fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") try: printer = Network(ip_caja, timeout=10) except: print("Impresora no conectada") return False with EscposIO(printer) as p: p.printer.set(align='center') p.printer.image("logo.png") p.writelines("Pizzeria y Hamburgeseria", height=2, width=1, text_type='bold', align='center') p.writelines('Plaza San lazaro, 9, local 2', font='a', align='center') p.writelines('NIF: 52527453F', font='b', align='center') p.writelines('Tlf: 958 092 462', font='b', height=2, width=3, align='center') p.writelines('------------------------------------------', align='center') p.writelines('FECHA', height=2, width=2, font='a', align='center') p.writelines(fecha, height=2, width=1, font='b', align='center') p.writelines("Num: %d" % num, text_type='bold', font='a', align='center') p.writelines('------------------------------------------', align='center') for ln in lineas: tipo = ln["tipo"].upper() if ln['tipo'] in ( "pizzas, burger") else "" if tipo == "": p.writelines("{0: >3} {1: <33} {2:0.2f}".format( ln['cant'], ln['text'], float(ln['total'])), align='center', text_type='bold') else: p.writelines("{0: >3} {1: <7} {2: <25} {3:0.2f}".format( ln['cant'], tipo, ln['text'], float(ln['total'])), align='center', text_type='bold') if ln['des'].strip() != "": des = ln['des'] chunks, chunk_size = len(des), 34 sub = [ des[i:i + chunk_size] for i in range(0, chunks, chunk_size) ] for s in sub: p.writelines("{0: <36}".format(s), font="a", align='center') p.writelines("") p.writelines("Total: {0:0.2f} ".format(total), align='right', height=2) p.writelines("Efectivo: {0:0.2f} ".format(efectivo), align='right') p.writelines( "Cambio: {0:0.2f} ".format(cambio), align='right', ) p.writelines("") p.writelines("Factura simplificada", text_type='bold', height=2, align='center') p.writelines("Iva incluido", text_type='bold', height=2, align='center') p.writelines("") p.writelines("Gracias por su visita", text_type='bold', height=2, align='center') if cl != None and len(cl) > 0: p.writelines("------------------------------------------", align='center') p.writelines("Datos del cliente", align="center", height=2, text_type='bold') p.writelines("------------------------------------------", align='center') cl = cl[0] p.writelines(cl['nombre'], align='left', width=2, height=2) if "direcciones" in cl: direcciones = cl["direcciones"] text_dir = "" if len(direcciones) > 0: text_dir = direcciones[0]['direccion'] for l in direcciones: if cl["direccion"] == l["id"]: text_dir = l["direccion"] p.writelines(text_dir, align='left', width=2, height=2) p.writelines("") p.writelines(cl['telefono'], align='left', width=2, height=2) p.writelines("") p.writelines(cl['nota'], align='left', width=2, height=2) p.writelines("") p.writelines("")
def imprimirTicket(self, p, num, lineas, fecha, total, efectivo, cambio, cl=None): if type(fecha) is datetime: fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") else: fecha = datetime.strptime(fecha, "%Y-%m-%d %H:%M:%S.%f") fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") printer = Network(ip_caja, timeout=10) with EscposIO(printer) as p: p.printer.set(align='center') p.printer.image("logo.png") p.writelines("Pizzeria y Hamburgeseria", height=2, width=1, text_type='bold', align='center') p.writelines('Plaza San lazaro, 9, local 2', font='a', align='center') p.writelines('NIF: 52527453F', font='b', align='center') p.writelines('Tlf: 958 092 462', font='b', height=2, width=3, align='center') p.writelines('------------------------------------------', align='center') p.writelines('FECHA', height=2, width=2, font='a', align='center') p.writelines(fecha, height=2, width=1, font='b', align='center') p.writelines("Num: %d" % num, text_type='bold', font='a', align='center') p.writelines('------------------------------------------', align='center') for ln in lineas: tipo = ln.tipo if ln.tipo in ("pizzas, burger") else "" if tipo == "": p.writelines("{0: >3} {1: <33} {2:0.2f}".format( ln.cant, ln.text, float(ln.total)), align='center', text_type='bold') else: p.writelines("{0: >3} {1: <7} {2: <25} {3:0.2f}".format( ln.cant, tipo, ln.text, float(ln.total)), align='center', text_type='bold') if ln.des.strip() != "": des = ln.des chunks, chunk_size = len(des), 34 sub = [ des[i:i + chunk_size] for i in range(0, chunks, chunk_size) ] for s in sub: p.writelines("{0: <36}".format(s), font="a", align='center') p.writelines("") p.writelines("Total: {0:0.2f} ".format(total), align='right', height=2) p.writelines("Efectivo: {0:0.2f} ".format(efectivo), align='right') p.writelines( "Cambio: {0:0.2f} ".format(cambio), align='right', ) p.writelines("") p.writelines("Factura simplificada", text_type='bold', height=2, align='center') p.writelines("Iva incluido", text_type='bold', height=2, align='center') p.writelines("") p.writelines("Gracias por su visita", text_type='bold', height=2, align='center') if cl != None and len(cl) > 0: p.writelines("------------------------------------------", align='center') p.writelines("Datos del cliente", align="center", height=2, text_type='bold') p.writelines("------------------------------------------", align='center') cl = cl[0] p.writelines(cl.nombre, align='left', width=2, height=2) p.writelines(cl.direcciones.get(query="id=%d" % cl.direccion)[0].direccion, align='left', width=2, height=2) p.writelines(cl.nota, align='left', width=2, height=2) p.writelines(cl.telefono, align='left', width=2, height=2) p.writelines("") p.writelines("")
def cariekstre(self): p = Network("192.168.2.222") p._raw(self.d.output) print "elma" p = None print p
def perform_create(self, serializer): lateness = serializer.save() printing = self.request.query_params.get('print', None) lateness_settings = get_settings() lateness_count = self.get_queryset().filter( student=lateness.student, justified=False, ).count() if lateness_settings.printer and printing: try: printer = Network(lateness_settings.printer) if not settings.DEBUG else Dummy() printer.charcode('USA') printer.set(align='CENTER', text_type='B') printer.text('RETARD\n') printer.set(align='LEFT') absence_dt = lateness.datetime_creation.astimezone(timezone.get_default_timezone()) count_or_justified = "Retard justifié" if lateness.justified else "Nombre de retards: " if not lateness.justified: count_or_justified += "%i" % lateness_count printer.text('\n%s %s\n%s\n%s\n%s\nBonne journée !' % ( unidecode(lateness.student.last_name), unidecode(lateness.student.first_name), lateness.student.classe.compact_str, absence_dt.strftime("%H:%M - %d/%m/%Y"), count_or_justified )) if settings.DEBUG: print(printer.output) printer.cut() printer.close() except OSError: pass for trigger in SanctionTriggerModel.objects.filter( teaching=lateness.student.teaching, year__year=lateness.student.classe.year ): count_first = trigger.lateness_count_trigger_first count_trigger = trigger.lateness_count_trigger if lateness_count < count_first or ( lateness_count > count_first and (lateness_count - count_first) % count_trigger != 0 ): continue lateness.has_sanction = True if trigger.only_warn: lateness.save() continue from dossier_eleve.models import CasEleve, SanctionDecisionDisciplinaire sanction = SanctionDecisionDisciplinaire.objects.get(id=trigger.sanction_id) today = datetime.datetime.today() day_shift = 6 + trigger.next_week_day day = today + datetime.timedelta(days=(day_shift - today.isoweekday()) % (6 + trigger.delay) + 1) day.replace(hour=trigger.sanction_time.hour, minute=trigger.sanction_time.minute) cas = CasEleve.objects.create( matricule=lateness.student, name=lateness.student.display, demandeur=self.request.user.get_full_name(), sanction_decision=sanction, explication_commentaire="Sanction pour cause de retard.", sanction_faite=False, datetime_sanction=day, created_by=self.request.user ) cas.visible_by_groups.set(Group.objects.all()) lateness.sanction_id = cas.id lateness.save() if lateness_settings.notify_responsible: responsibles = get_resp_emails(lateness.student) context = {"lateness": lateness, "lateness_count": lateness_count} send_email( responsibles, "[Retard]%s %s %s" % ( "[Sanction]" if lateness.has_sanction else "", lateness.student.fullname, lateness.student.classe.compact_str ), "lateness/lateness_email.html", context=context )
def start(): global REDISIP global KEY global PRINTERIP cache = redis.StrictRedis(REDISIP,6379) key = KEY message = cache.get(key) dict = eval(message) print dict #init push printer character if dict.get('orderType') == 1: Big = dict.get('data') Bigstr = str(Big) Bigdict = eval(Bigstr) title = json.dumps(Bigdict.get('storeName'),encoding='UTF-8',ensure_ascii=False) titlefull = title.replace("\"","") orderId = Bigdict.get('orderId') machineId = Bigdict.get('machineId') cashier = Bigdict.get('cashier') orderTime = Bigdict.get('orderTime') takefoodNum = Bigdict.get('takefoodNum') #取餐号 kindchagne = json.dumps(Bigdict.get('kind'),encoding='UTF-8',ensure_ascii=False) kind = kindchagne.replace("\"","") #堂食 / 外带 try: print "init printer" p = Network(PRINTERIP,timeout=10000) p.set(align='center',font='a',text_type='normal',height=1,width=1,invert=False, smooth=False,flip=False) p.text(u"欢迎光临真功夫[%s]\n\n".encode('gbk') % titlefull) p.set(align='center',font='B',text_type='B',height=2,width=2,invert=False, smooth=False,flip=False) p.text(u"取货单\n\n".encode('gbk')) p.set(align='center',font='a',text_type='normal',height=1,width=1,invert=False, smooth=False,flip=False) p.text(u"单号:[%s]\t 机号: [%s]\n 收银员: [%s]\n ".encode('gbk') % (orderId,machineId,cashier)) p.text(u"打单时间: [%s]\n\n".encode('gbk') % orderTime) p.set(align='center',font='B',text_type='B',height=2,width=2,invert=False, smooth=False,flip=False) p.text(u"取餐号: %s\n\n".encode('gbk') % (takefoodNum)) p.set(align='center',font='a',text_type='normal',height=1,width=1,invert=False, smooth=False,flip=False) p.text(u"[%s]合计 Total\n".encode('gbk') % (kind)) p.set(align='left',font='a',text_type='normal',height=1,width=1,density=8,invert=False, smooth=False,flip=False) p.text(u"数量\t\t产品名称\r\n".encode('gbk')) prodList = Bigdict.get('prodList') for prodListdict in prodList: foodnum = prodListdict.get('num') #print foodnum foodnamechagne = json.dumps(prodListdict.get('name'),encoding='UTF-8',ensure_ascii=False) foodname = foodnamechagne.replace("\"","") #print foodname p.text(u"%s\t%s\n".encode('gbk') % (foodnum,foodname)) p.cut() except Exception as e: print ("connect printer %s") % (e) print ("please look at the bus about printer_kitchen alive")
class Printer: printer = None def __init__(self, ip): self.printer = Network(ip) def Test(self): return True def Print(self, text, convertesc, cutprint, selfont): if self.ConvertBool(convertesc): text = text.replace("\\n", "\n") text = text.replace("\\t", "\t") text = text.replace("\\\\", chr(92)) # text = text.replace("\\", "***") self.printer.set(font=selfont) self.printer.text(text) self.printer.set(font='a') if self.ConvertBool(cutprint): self.printer.cut() def PrintBoxTag(self, caseNumbers, Organisation, inDate, outDate, Contents, Serials): img = qrcode.make("ID" + str(caseNumbers), box_size=8) img.save("out.png") self.printer.set(align=u'center', font='a') self.printer.text("Hospitality Technology\n") self.printer.text("Hardware Department\n") self.printer.image("out.png") self.printer.set(align=u'left') caseNumberString = "" for caseNo in caseNumbers: caseNumberString += " " + caseNo + "\n" contentString = "" for hardware in Contents: contentString += " " + hardware + "\n" serialString = "" for serial in Serials: serialString += " " + serial + "\n" self.printer.text("Property : " + Organisation + "\n") self.printer.text("Received Date : " + inDate + "\n") self.printer.text("Released Date : " + outDate + "\n") self.printer.text("Case No :\n") self.printer.text(caseNumberString + "\n") self.printer.text("Contents :\n") self.printer.text(contentString + "\n") self.printer.text("Serials :\n") self.printer.text(serialString + "\n") self.printer.cut() def StressTest(self, line_count): chararr = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" ] for y in range(line_count): string = "" for x in range(42): string += chararr[randrange(0, len(chararr) - 1)] self.printer.text(string) self.printer.text("\n\n") self.printer.cut() def AdvancedStressTest(self, line_count, infont, alphabet, numbers, specialChars, CutAfterPrint): alphabet = self.ConvertBool(alphabet) numbers = self.ConvertBool(numbers) specialChars = self.ConvertBool(specialChars) CutAfterPrint = self.ConvertBool(CutAfterPrint) finalArray = [] alphabetArray = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] numberArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] specialCharsArray = [ "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "=", "+", "\\", "/", "<", ">", ".", ",", '"', "'", ";", ":", "[", "]", "|" ] if numbers: finalArray.extend(numberArray) if alphabet: finalArray.extend(alphabetArray) if specialChars: finalArray.extend(specialCharsArray) self.printer.set(font=infont) for y in range(int(line_count)): string = "" for x in range(42): string += choice(finalArray) self.printer.text(string) if CutAfterPrint: self.printer.text("\n\n") self.printer.cut() self.printer.set(font='a') def ConvertBool(self, instr): if (instr.__eq__("false")): return False return True
from escpos.printer import Network kitchen = Network("192.168.88.195") #Printer IP Address kitchen.text("Hello World\n") kitchen.barcode('1324354657687', 'EAN13', 64, 2, '', '') kitchen.cut()
height=2) p.writelines(cl.nota, align='left', width=2, height=2) p.writelines(cl.telefono, align='left', width=2, height=2) p.writelines("") p.writelines("") if __name__ == '__main__': import sys import os import locale locale.setlocale(locale.LC_TIME, "es_ES") # swedish reload(sys) sys.setdefaultencoding('UTF8') printer = Network(ip_caja) fecha = datetime.now().strftime("El %a %d-%B a las (%H:%M)") with EscposIO(printer) as p: p.writelines('BTres', font='a', height=4, width=4, align='center') p.writelines("Pizzeria y Hamburgeseria", height=2, width=1, text_type='bold', align='center') p.writelines('Plaza San lazaro, 9, local 2', font='a', align='center') p.writelines('NIF: 52527453F', font='b', align='center') p.writelines('------------------------------------------', align='center') p.writelines('FECHA', height=2, width=2, font='a', align='center') p.writelines(fecha, height=2, width=1, font='b', align='center') p.writelines('------------------------------------------',
def print_ticket_network(data): try: p = Network(GATE['printer_ip_address']) except Exception as e: logging.error('Failed to print ticket ' + data['nomor_barcode'] + ' ' + str(e)) send_notification( 'Pengunjung di ' + GATE['nama'] + ' gagal print tiket. Informasikan nomor barcode kepada pengunjung. ' + data['nomor_barcode']) return try: p.set(align='center') p.text("TIKET PARKIR\n") p.set(height=2, align='center') p.text(SETTING['nama_lokasi'] + "\n\n") p.set(align='left') p.text('TANGGAL : ' + datetime.datetime.strptime( data['time_in'][:10], '%Y-%m-%d').strftime('%d %b %Y') + "\n") p.text('JAM : ' + data['time_in'][11:] + "\n\n") p.set(align='center') p.barcode(data['nomor_barcode'], 'CODE39', function_type='A', height=100, width=4, pos='BELOW', align_ct=True) p.text("\n") p.text(SETTING['info_tambahan_tiket']) p.cut() except Exception as e: logging.error('Failed to print ticket ' + data['nomor_barcode'] + ' ' + str(e)) send_notification( 'Pengunjung di ' + GATE['nama'] + ' gagal print tiket. Informasikan nomor barcode kepada pengunjung. ' + data['nomor_barcode']) return logging.info('Ticket printed ' + data['nomor_barcode'])
def imprimirTicket(self, num, camarero, fecha, mesa, total, efectivo, cambio, lineas): if type(fecha) is datetime: fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") else: fecha = datetime.strptime(fecha, "%Y/%m/%d %H:%M") fecha = fecha.strftime("El %a %d-%B a las (%H:%M)") try: if self.tipo == "Network": printer = Network(self.ip_caja, timeout=1) if self.tipo == "Usb": printer = Usb(*self.usb) if self.tipo == "File": printer = File(self.url) with EscposIO(printer) as p: p.printer.codepage = 'cp858' p.printer._raw(escpos.CHARCODE_PC852) p.printer.image("logo.png") p.writelines('Calle Dr Mesa Moles, 2', font='a', align='center') p.writelines('18012 Granada', font='a', align='center') p.writelines('NIF: B18616201', font='b', align='center') p.writelines('------------------------------------------', align='center') p.writelines(fecha, height=2, width=1, font='b', align='center') p.writelines("Num Ticket: %d" % num, font='a', align='center') p.writelines("Camarero: %s" % camarero, font='a', align='center') p.writelines("Mesa: %s" % mesa, font='a', align='center') p.writelines('------------------------------------------', align='center') for ln in lineas: p.writelines( "{0: >3} {1: <20} {2:5.2f} € {3:6.2f} €".format( ln['can'], ln['nombre'], float(ln['precio']), float(ln['totallinea'])), density=1, align='center') p.writelines("", text_type='bold', font='b', align='center') p.writelines("Total: {0:0.2f} €".format(float(total)), align='right', height=2) p.writelines("Efectivo: {0:0.2f} €".format(float(efectivo)), align='right') p.writelines( "Cambio: {0:0.2f} €".format(float(cambio)), align='right', ) p.writelines("", text_type='bold', font='a', align='center') p.writelines("Factura simplificada", text_type='bold', font='a', align='center') p.writelines("Iva incluido", text_type='bold', font='a', align='center') p.writelines("Gracias por su visita", font='a', align='center') except Exception as e: print("[ERROR ] %s" % e)
def pos_print(order=None): if order is None: order = [] try: epson = Network("192.168.1.100") epson.image("/home/sysop/pos/rosie.png") bar = '0000' price = 0 for m in order: epson.set(height=2, width=2, align='center') epson.text('Your PIN\n') epson.set(font='a', height=3, width=3, align='center') epson.text(str(m[3]) + '\n') bar = str(m[3]) epson.set(font='a', height=2, width=2, align='left', text_type='u2') epson.text(' Order \n') epson.set(text_type='normal') epson.text(str(m[0])) if int(m[0]) > 1: epson.text(' Cups of Donuts') price = int(m[0]) * 4.76 epson.text(' $' + str(price) + '\n') price = int(m[0]) * 4.7619 else: epson.text(' Cup of Donuts') epson.text(' $4.76\n') price = 4.7619 n = str(m[1]) if int(n[0]) > 1: p = int(n[0]) - 1 epson.text(str(p) + ' ') epson.text('Mountain Dew') p2 = p * 1.9047 p = p * 1.90 price = price + p2 epson.text(' $' + str(p) + '0\n') if int(n[1]) > 0: epson.text(n[1] + ' ') epson.text('Root Beer') p = int(n[1]) * 1.90 p2 = int(n[1]) * 1.9047 price = price + p2 epson.text(' $' + str(p) + '0\n') if int(n[2]) > 0: epson.text(n[2] + ' ') epson.text('Pepsi') p = int(n[1]) * 1.90 p2 = int(n[1]) * 1.9047 price = price + p2 epson.text(' $' + str(p) + '0\n') if int(n[3]) > 0: epson.text(n[3] + ' ') epson.text('7 Up') p = int(n[1]) * 1.90 p2 = int(n[1]) * 1.9047 price = price + p2 epson.text(' $' + str(p) + '0\n') gst = price * .05 nice_gst = math.ceil(gst * 100) / 100 epson.text(' GST: $' + str(nice_gst) + '\n') print(nice_gst) price = price + gst tot = math.ceil(price * 100) / 100 epson.text(' Total: $' + str(tot) + '0\n') print(tot) epson.text('\n\n') epson.set(font='a', height=2, width=2, align='center') epson.text('THANK YOU\n') epson.set(font='a', height=1, width=1, align='center') epson.barcode(bar, 'CODE128', function_type="B") epson.cut() except Exception as ex: print(ex)
"bericht": reserveringTeken + " " + str(reservering['numberOfPeople']) + "p om " + reserveringTijd + " - " + reserveringNaam }) for ticket in reservering['tickets']: if ticket["title"] == "High Tea": reserveringPrinten.append({"opmerking": "^^ High Tea"}) aantalReserveringen += 1 if reserveringPrinten: logging.debug('%s reserveringen worden geprint', aantalReserveringen) kitchen = Network(os.getenv("IP_PRINTER")) #Printer IP Address output = Dummy() output.text("Reservering Update (" + tijdVandaagPrint + " " + datumVandaagPrint + ")\n\n") # Maak tekst zwart output._raw(b'\x1B\x35' + b'\x01') for reserveringPrint in reserveringPrinten: if reserveringPrint.get("bericht"): output.text(reserveringPrint.get("bericht") + "\n") if reserveringPrint.get("opmerking"): # Maak tekst rood
def __init__(self, ip): self.printer = Network(ip)
def cariekstre(self): p = Network("192.168.2.222") p._raw(self.d.output) print "elma" p=None print p
def thermalPrint(self): "Prints the pwd on the thermal printer at the specified ip" if self.printerIp: p = Network(self.printerIp) p.set(align='center', text_type='bold', width=2, height=2) p.text("fZone Guest WiFI\n\n") p.set() p.text('\tDate:\t' + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") + '\n') p.text('\tSSID:\t' + self.radioSSID + '\n') p.text('\tPwd:\t' + self.pwd + '\n') p.text('\n') p.set(align='center') p.qr('WIFI:T:WPA;S:' + self.radioSSID + ';P:' + self.pwd + ';;', size=6, native=False) p.text('Scan me to login!') p.cut() pass
def _connect_network(self, **kwargs): """Initializes the __printer instance with Network printer @param: ip of printer @retrurn: Network() """ return Network(kwargs['ip'])