def print_job_checker(): """ Prints out all jobs in the print queue every 5 seconds """ jobs = [1] while jobs: jobs = [] for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1): flags, desc, name, comment = p phandle = win32print.OpenPrinter(name) print_jobs = win32print.EnumJobs(phandle, 0, -1, 1) if print_jobs: jobs.extend(list(print_jobs)) for job in print_jobs: print("printer name => " + name) document = job["pDocument"] print("Document name => " + document) win32print.ClosePrinter(phandle) time.sleep(5) print("No more jobs!")
def begin_document(self, desc="MSWinPrint.py print job"): # open the printer if self.printer is None: self.printer = win32print.GetDefaultPrinter() self.hprinter = win32print.OpenPrinter(self.printer) # load default settings devmode = win32print.GetPrinter(self.hprinter, 8)["pDevMode"] # change paper size and orientation if self.papersize is not None: if type(self.papersize) is int: devmode.PaperSize = self.papersize else: devmode.PaperSize = paper_sizes[self.papersize] if self.orientation is not None: devmode.Orientation = orientations[self.orientation] if self.duplex is not None: devmode.Duplex = duplexes[self.duplex] # create dc using new settings self.hdc = win32gui.CreateDC("WINSPOOL", self.printer, devmode) self.dc = win32ui.CreateDCFromHandle(self.hdc) # self.dc = win32ui.CreateDC() # if self.printer is not None: # self.dc.CreatePrinterDC(self.printer) # else: # self.dc.CreatePrinterDC() #self.dc.SetMapMode(win32con.MM_TWIPS) # hundredths of inches self.dc.SetMapMode(win32con.MM_HIMETRIC) self.dc.StartDoc(desc) self.pen = win32ui.CreatePen(0, int(scale_factor), 0L) self.dc.SelectObject(self.pen) self.page = 1
def printCode(): c = generateCode() printer_name = win32print.GetDefaultPrinter() print(printer_name) hPrinter = win32print.OpenPrinter(printer_name) # print(hPrinter) if sys.version_info >= (3,): raw_data = bytes(c, "utf-8") # print('$$$$$$', c) else: raw_data = c # print('$$$$$$', c) try: hJob = win32print.StartDocPrinter(hPrinter, 1, (c, None, "RAW")) # print('$$$$$$', c) try: win32print.StartPagePrinter(hPrinter) win32print.WritePrinter(hPrinter, raw_data) win32print.EndPagePrinter(hPrinter) finally: win32print.EndDocPrinter(hPrinter) finally: win32print.ClosePrinter(hPrinter)
def printlabelonwindows(printer, labelmodelfile, charSep, parameters): contenu = "" with open(labelmodelfile) as fichierEtiq: for line in fichierEtiq: contenu += line + "\r\n" for paramName, value in parameters: if contenu.find(charSep + paramName.lower() + charSep) != -1: if (value is not None): contenu = contenu.replace( charSep + paramName.lower() + charSep, str(value).replace("é", "\\82").replace("à", "\\85").replace( "î", "\\8C")) else: contenu = contenu.replace( charSep + paramName.lower() + charSep, "") #print(sys.version_info) if sys.version_info >= (3, ): raw_data = bytes(contenu, "utf-8") else: raw_data = contenu hPrinter = win32print.OpenPrinter(printer) try: hJob = win32print.StartDocPrinter(hPrinter, 1, ("print", None, "RAW")) try: win32print.StartPagePrinter(hPrinter) win32print.WritePrinter(hPrinter, raw_data) win32print.EndPagePrinter(hPrinter) finally: win32print.EndDocPrinter(hPrinter) finally: win32print.ClosePrinter(hPrinter)
def PrintAction(event=None): PRINTER_DEFAULTS = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter(_printer.get(), PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) properties['pDevMode'].Color = 1 if str(_color.get()) == "Color" else 2 properties['pDevMode'].Copies = 1 win32print.SetPrinter(pHandle, 2, properties, 0) if not _filename: messagebox.showerror("Error", "No File Selected") return elif not _printer.get(): messagebox.showerror("Error", "No Printer Selected") return try: #win32print.SetDefaultPrinter(_printer.get()) win32api.ShellExecute(0, "print", _filename, None, ".", 0) win32print.ClosePrinter(pHandle) except: pass messagebox.showerror("Error", "There was an error printing the file :(")
def main(): printer_name = "HP LaserJet 2420 PCL6 Class Driver" # or get_printer_names()[0] prn = win32print.OpenPrinter(printer_name) error = printer_errorneous_state(prn) if error: print("ERROR occurred: ", error) else: print("Printer OK...") # Do the real workS previusStatus = 0 counter = 0 previusJob = {} while True: jobs = [] print_jobs = win32print.EnumJobs(prn, 0, 1, 2) if print_jobs: jobs.extend(list(print_jobs)) if (len(jobs) > 0): if (previusStatus == 0): print("Starting printing") counter = counter + 1 previusStatus = 1 previusJob = printCatching(jobs) else: if (previusStatus == 1): print("User " + previusJob["pUserName"] + " have printed " + str(previusJob["PagesPrinted"]) + " Pages") print("Finish printing") print(counter) counter = 0 previusStatus = 0 win32print.ClosePrinter(prn)
def connectToPrinter(self, printerParam): #determine first if it is a usb or network printer if printerParam['connectionMethod'] == 'network': self.printer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.printer.settimeout(60) try: self.printer.connect(( printerParam['host'], printerParam['port'], )) except: self.connectionStatus = False self.connectionDiagnostic = "The printer did not respond on {0} and port {1}".format( printerParam['host'], printerParam['port']) return self.connectionStatus = True self.connectionDiagnostic = 'Successfully connected' if printerParam['connectionMethod'] == 'usb': self.printer = win32print.OpenPrinter( printerParam['printerDriverName']) self.connectionDiagnostic = 'Success' self.connectionStatus = True
def printOrden(self): numTortillas = '' cantidad = 0 totalOrdenTaquero = '' totalOrdenTotillera = '' totalOrdenTomar = '' ordenes = self.request.data.get('ordenesImprimir') mesa = self.request.data.get('mesa') mesero = self.request.data.get('nombreMesero') for orden in ordenes: last = len(orden) - 1 for index, platillo in enumerate(orden): cantidad = platillo.split(' ')[0] if not 'B-' in platillo: if index == last: totalOrdenTaquero += '\n{0} \n--------------\n'.format( platillo) else: totalOrdenTaquero += '\n{0}'.format(platillo) if 'Quesadilla' in platillo or 'Q' in platillo: totalOrdenTotillera += '\n{0} totillas para Quesadillas'.format( cantidad) elif 'Taco' in platillo or 'Tacos' in platillo or 'T' in platillo: totalOrdenTotillera += '\n{0} totillas para Tacos'.format( cantidad) elif 'B-' in platillo: totalOrdenTomar += '\n{0}'.format(platillo) # Epson Bebidas y Caja if totalOrdenTomar != '': print_final_bebidas = """ \t Mesero: {mesero} Mesa # {mesa} \r ---------------- {totalOrdenTomar} """.format(mesero=mesero, mesa=mesa, totalOrdenTomar=totalOrdenTomar) printer = win32print.OpenPrinter('EPSON TM-T88V 1') jid = win32print.StartDocPrinter(printer, 1, ('TEST DOC', None, 'RAW')) bytes = win32print.WritePrinter(printer, print_final_bebidas) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) # Cortar hDC = win32ui.CreateDC() hDC.CreatePrinterDC('EPSON TM-T88V 1') hDC.StartDoc("Test doc") hDC.StartPage() hDC.EndPage() hDC.EndDoc() if totalOrdenTaquero != '': print_final_taquero = """ \t Mesero: {mesero} Mesa # {mesa} \r ---------------- {totalOrdenTaquero} """.format(mesero=mesero, mesa=mesa, totalOrdenTaquero=totalOrdenTaquero) # Epson Taquero printer = win32print.OpenPrinter('EPSON TM-T88V 3') jid = win32print.StartDocPrinter(printer, 1, ('TEST DOC', None, 'RAW')) bytes = win32print.WritePrinter(printer, print_final_taquero) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) # Cortar hDC = win32ui.CreateDC() hDC.CreatePrinterDC('EPSON TM-T88V 3') hDC.StartDoc("Test doc") hDC.StartPage() hDC.EndPage() hDC.EndDoc() if totalOrdenTotillera != '': print_final_tortillera = """ \t Mesero: {mesero} Mesa # {mesa} \r ---------------- {totalOrdenTotillera} """.format(mesero=mesero, mesa=mesa, totalOrdenTotillera=totalOrdenTotillera) # Epson Tortillera printer = win32print.OpenPrinter('EPSON TM-T88V 2') jid = win32print.StartDocPrinter(printer, 1, ('TEST DOC', None, 'RAW')) bytes = win32print.WritePrinter(printer, print_final_tortillera) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) # Cortar hDC = win32ui.CreateDC() hDC.CreatePrinterDC('EPSON TM-T88V 2') hDC.StartDoc("Test doc") hDC.StartPage() hDC.EndPage() hDC.EndDoc()
import win32gui import win32print from lib.shopping_list_interface import ShoppingListInterface interface = ShoppingListInterface() # if you just want to use the default printer, you need # to retrieve its name. printer = win32print.GetDefaultPrinter() # open the printer. import win32ui from win32con import DMPAPER_A5, DMPAPER_A5_ROTATED, DMRES_MEDIUM, DMRES_LOW hprinter = win32print.OpenPrinter('HP Deskjet 2540 series (sieć)') # hprinter = win32print.OpenPrinter('Microsoft Print to PDF') # retrieve default settings. this code does not work on # win95/98, as GetPrinter does not accept two devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] # change paper size and orientation # constants are available here: # http://msdn.microsoft.com/library/default.asp? # url=/library/en-us/intl/nls_Paper_Sizes.asp # number 10 envelope is 20 devmode.PaperSize = DMPAPER_A5 devmode.PrintQuality = 300 # devmode.YResolution = 300 # devmode.XResolution = 300
def printOut(self, file_name): # List available printers #print("Available printers") #print(win32print.EnumPrinters(0,"None",1)) #print(win32print.EnumPrinters(1,"None",2)) #print(win32print.EnumPrinters(3,"None",1)[4]) #print(win32print.EnumPrinters(3,"None",5)) # Use Default Printer #printer_name = win32print.GetDefaultPrinter () printer_name = "MITSUBISHI CP70D Series(USB)" print("Printer: " + printer_name) hprinter = win32print.OpenPrinter(printer_name, {"DesiredAccess": win32print.PRINTER_ALL_ACCESS}) devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] # DEVMODE devmodeSize=win32print.DocumentProperties(0, hprinter, printer_name, None, None, 0) devmode = pywintypes.DEVMODEType(devmodeSize - pywintypes.DEVMODEType().Size) #devmode.Fields = devmode.Fields|win32con.DM_ORIENTATION|win32con.DM_COPIES win32print.DocumentProperties(0, hprinter, printer_name, devmode, devmode, 0) ''' try: win32print.SetPrinter(hprinter, 2, properties, 0) except pywintypes.error, err: print(err[2]) #sys.exit() ''' gDC = win32gui.CreateDC("WINSPOOL", printer_name, devmode) hDC = win32ui.CreateDCFromHandle(gDC) self.printable_area = hDC.GetDeviceCaps (self.HORZRES), hDC.GetDeviceCaps (self.VERTRES) print "printable_area",self.printable_area printer_size = hDC.GetDeviceCaps (self.PHYSICALWIDTH), hDC.GetDeviceCaps (self.PHYSICALHEIGHT) print "printer_size",printer_size printer_margins = hDC.GetDeviceCaps (self.PHYSICALOFFSETX), hDC.GetDeviceCaps (self.PHYSICALOFFSETY) print "printer_margins",printer_margins bmp = Image.open (file_name) print "bmp.size[0]",bmp.size[0]," bmp.size[1]",bmp.size[1] #if bmp.size[0] > bmp.size[1]: #bmp = bmp.rotate (90) ratios = [1.0 * self.printable_area[0] / bmp.size[0], 1.0 * self.printable_area[1] / bmp.size[1]] print "ratios",ratios scale = min (ratios) print "scale",scale hDC.StartDoc (file_name) hDC.StartPage () dib = ImageWin.Dib (bmp) scaled_width, scaled_height = [int (scale * i) for i in bmp.size] print "scaled width",scaled_width," scaled height",scaled_height x1 = int ((printer_size[0] - scaled_width) / 2) y1 = int ((printer_size[1] - scaled_height) / 2) x2 = x1 + scaled_width y2 = y1 + scaled_height print "x1, y1, x2, y2",x1, y1, x2, y2 #dib.draw (hDC.GetHandleOutput (), (x1-5, y1+38, x2-25, y2-24)) #dib.draw (hDC.GetHandleOutput (), (x1-5, y1+38, x2, y2)) dib.draw (hDC.GetHandleOutput (), (0, 0, scaled_width, scaled_height)) hDC.EndPage () hDC.EndDoc () hDC.DeleteDC ()
import os, sys import win32print p = win32print.OpenPrinter('OneNote') job = win32print.StartDocPrinter(p, 1, ("test priniting message", None, "RAW")) win32print.StartPagePrinter(p) win32print.WritePrinter(p, 1235468) win32print.EndPagePrinter(p)
def main(argv): inputfile = r'C:\Users\sci\Downloads\dbch-print.jpg' bUseSambaFolder = False sambaFolder = r'\\192.168.1.152\smilecooker' sambaUser = r'whatEver\guest' sambaPassword = r'guest' sambaDriveLetter = r'x:' printer_name = '' paperWidth = 360 paperLength = 360 rotate = 0 objectFit = 'cover' try: opts, args = getopt.getopt(argv, "hi:f:u:p:d:h:w:l:r:o:", [ "ifile=", "sambafolder=", "sambauser="******"sambapassword="******"sambadriveletter=", "printer=", "width=", "length=", "rotate=", "object-fit=" ]) except getopt.GetoptError: help() sys.exit(2) for opt, arg in opts: if opt == '-h': help() sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-f", "--sambafolder"): sambaFolder = arg bUseSambaFolder = True elif opt in ("-u", "--sambauser"): sambaUser = arg elif opt in ("-p", "--sambapassword"): sambaPassword = arg elif opt in ("-d", "--sambadriveletter"): sambaDriveLetter = arg elif opt in ("-h", "--printer"): printer_name = arg elif opt in ("-w", "--width"): paperWidth = int(arg) elif opt in ("-l", "--length"): paperLength = int(arg) elif opt in ("-r", "--rotate"): rotate = int(arg) elif opt in ("-o", "--object-fit"): if arg == 'cover' or arg == 'contain': objectFit = arg else: print 'Value ' + arg + ' is not available for object-fit. Possible values are \'cover\' or \'contain\'' print 'Input file is ', inputfile sambaCommand = r'net use ' + sambaDriveLetter + ' ' + sambaFolder + ' /user:'******' ' + sambaPassword if bUseSambaFolder: print 'Input samba command is ', sambaCommand subprocess.call(sambaCommand, shell=True) if printer_name == '': printer_name = win32print.GetDefaultPrinter() # # Constants for GetDeviceCaps # # # HORZRES / VERTRES = printable area # HORZRES = 8 VERTRES = 10 # # LOGPIXELS = dots per inch # LOGPIXELSX = 88 LOGPIXELSY = 90 # # PHYSICALWIDTH/HEIGHT = total area # PHYSICALWIDTH = 110 PHYSICALHEIGHT = 111 # # PHYSICALOFFSETX/Y = left / top margin # PHYSICALOFFSETX = 112 PHYSICALOFFSETY = 113 file_name = inputfile # # You can only write a Device-independent bitmap # directly to a Windows device context; therefore # we need (for ease) to use the Python Imaging # Library to manipulate the image. # # Create a device context from a named printer # and assess the printable size of the paper. # printer = win32print.OpenPrinter( printer_name, {'DesiredAccess': win32print.PRINTER_ALL_ACCESS}) d = win32print.GetPrinter(printer, 2) devmode = d['pDevMode'] #print 'Status ', d['Status'] #for n in dir(devmode): # print "%s\t%s" % (n, getattr(devmode, n)) #if d[18]: #print "Printer not ready" #print ':'.join(x.encode('hex') for x in devmode.DriverData) devmode.PaperLength = paperWidth # in 0.1mm devmode.PaperWidth = paperLength # in 0.1mm # paper for square sticker # devmode.PaperLength = 381 # in 0.1mm # devmode.PaperWidth = 381 # in 0.1mm # paper for hello my name is #devmode.PaperLength = 2400 # in 0.1mm #devmode.PaperWidth = 1800 # in 0.1mm # paper for flipbook #devmode.PaperLength = 411 # in 0.1mm #devmode.PaperWidth = 1079 # in 0.1mm win32print.SetPrinter(printer, 2, d, 0) ### dmsize=win32print.DocumentProperties(0, printer, printer_name, None, None, 0) ### dmDriverExtra should be total size - fixed size ## driverextra=dmsize - pywintypes.DEVMODEType().Size ## need a better way to get DEVMODE.dmSize ## dm=pywintypes.DEVMODEType(driverextra) ## #win32print.DocumentProperties(0, printer, printer_name, dm, None, win32con.DM_IN_BUFFER) ## #for n in dir(dm): ## # print "%s\t%s" % (n, getattr(dm, n)) ## #dm.Fields=dm.Fields|win32con.DM_ORIENTATION|win32con.DM_COPIES ## #dm.Orientation=win32con.DMORIENT_LANDSCAPE ## #dm.Copies=2 ## #dm.PaperSize = 256 ## #dm.PaperLength = 381 ## #dm.PaperWidth = 381 ## for n in dir(dm): ## print "%s\t%s" % (n, getattr(dm, n)) ## win32print.DocumentProperties(0, printer, printer_name, dm, dm, win32con.DM_IN_BUFFER|win32con.DM_OUT_BUFFER) ## for n in dir(dm): ## print "%s\t%s" % (n, getattr(dm, n)) hDC = win32ui.CreateDC() hDC.CreatePrinterDC(printer_name) printable_area = hDC.GetDeviceCaps(HORZRES), hDC.GetDeviceCaps(VERTRES) printer_size = hDC.GetDeviceCaps(PHYSICALWIDTH), hDC.GetDeviceCaps( PHYSICALHEIGHT) printer_margins = hDC.GetDeviceCaps(PHYSICALOFFSETX), hDC.GetDeviceCaps( PHYSICALOFFSETY) #printable_area = (350*3, 1412*3) #printer_size = (350*3, 1412*3) print "printer area", printable_area print "printer size", printer_size print "printer margins", printer_margins # # Open the image, rotate it if it's wider than # it is high, and work out how much to multiply # each pixel by to get it as big as possible on # the page without distorting. # open(file_name) bmp = Image.open(file_name) #if bmp.size[0] > bmp.size[1]: # bmp = bmp.rotate (90) # bmp = bmp.rotate (180) if rotate != 0: bmp = bmp.rotate(rotate) print "bmp size", bmp.size ratios = [ 1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1] ] # fit to page if objectFit == "contain": scale = min(ratios) elif objectFit == "cover": scale = max(ratios) scaled_width, scaled_height = [int(scale * i) for i in bmp.size] bmp = bmp.resize((scaled_width, scaled_height), Image.HAMMING) x1 = int((printer_size[0] - scaled_width) / 2) y1 = int((printer_size[1] - scaled_height) / 2) x2 = x1 + scaled_width y2 = y1 + scaled_height # align right #x1 = (printer_size[0] - scaled_width) #x2 = x1 + scaled_width #scale = printer_size[1] / bmp.size[0] #x1 = 0 #y1 = 0 #x2 = 360 #y2 = 446 print "print rect: ", x1, y1, x2, y2 #sys.exit() # # Start the print job, and draw the bitmap to # the printer device at the scaled size. # try: hDC.StartDoc(file_name) hDC.StartPage() dib = ImageWin.Dib(bmp) dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2)) hDC.EndPage() hDC.EndDoc() hDC.DeleteDC() except win32ui.error as e: print "Unexpected error:", e
# -*- coding: utf-8 -*- import cairo import pango import pangocairo import sys import win32ui import win32print printer = win32print.GetDefaultPrinter() print printer phandle = win32print.OpenPrinter(printer) dc = win32ui.CreateDC() dc.CreatePrinterDC() dc.StartDoc("foo") dc.StartPage() surf = cairo.Win32PrintingSurface(dc.GetHandleAttrib()) context = cairo.Context(surf) #draw a background rectangle: context.rectangle(0, 0, 50, 50) context.set_source_rgb(0, 0, 0) context.fill() #get font families: font_map = pangocairo.cairo_font_map_get_default() families = font_map.list_families() # to see family names: #print [f.get_name() for f in font_map.list_families()]
def task(): # 获取默认打印机的工作状态 printer_name = win32print.GetDefaultPrinter() handle_printer = win32print.OpenPrinter(printer_name) # 获取打印机句柄 printer_info = win32print.GetPrinter(handle_printer, 2) # 调用相关函数进行信息查询 task_list = win32print.EnumJobs(handle_printer, 0, 10) # 参数(句柄,编文档号,枚举条数) return printer_info["cJobs"] # 获取当前打印机任务数目
# make sure the default printer is set appropriately PDF_CREATOR_PRINTER = 'PDFCreator' if getDefaultPrinter() != PDF_CREATOR_PRINTER: print 'setting default printer to %s' % PDF_CREATOR_PRINTER win32print.SetDefaultPrinter(PDF_CREATOR_PRINTER) # build the command line commandParams.append('/NoStart') inputFileExt = os.path.splitext(inputFile)[1].lower() if readOnly and inputFileExt == '.pdf': commandParams.append('/IF"%s"' % inputFile) commandParams.append('/OF"%s"' % outputFile) else: commandParams.append('/PF"%s"' % inputFile) command = ' '.join(commandParams) # execute the command print '\ncommand: %s' % command os.system(command) # wait until the printer queue becomes empty printer = win32print.OpenPrinter('PDFCreator') while True: if len(win32print.EnumJobs(printer, 0, 1, 2)) == 0: break time.sleep(.5)
def onBeginDoc(self): """ thanks to Chris Gonnerman for the recipe to set landscape orientation http://newcenturycomputers.net/projects/pythonicwindowsprinting.html """ # open the printer. if self.printerName is None: self.session.notice("Printing on Windows standard printer") else: self.session.notice("Printing on '%s'", self.printerName) hprinter = win32print.OpenPrinter(self.printerName) # retrieve default settings. this code has complications on # win95/98, I'm told, but I haven't tested it there. props = win32print.GetPrinter(hprinter, 2) devmode = props["pDevMode"] if devmode is None: # workaround, see http://lino.saffre-rumma.ee/news/477.html self.session.debug("%r has no pDevMode property", props) else: # change paper size and orientation # constants are available here: # http://msdn.microsoft.com/library/default.asp?\ # url=/library/en-us/intl/nls_Paper_Sizes.asp devmode.PaperSize = win32con.DMPAPER_A4 if self.isLandscape(): devmode.Orientation = win32con.DMORIENT_LANDSCAPE #print "Landscape" else: devmode.Orientation = win32con.DMORIENT_PORTRAIT #print "Portrait" # create dc using new settings. # first get the integer hDC value. # note that we need the name. self.dch = win32gui.CreateDC("WINSPOOL", self.printerName, devmode) # next create a PyCDC from the hDC. self.dc = win32ui.CreateDCFromHandle(self.dch) ## while True: ## h = win32print.OpenPrinter(win32print.GetDefaultPrinter()) ## t = win32print.GetPrinter(h) ## win32print.ClosePrinter(h) ## if t[18]: ## break ## print t ## if not console.confirm("not ready. retry?"): ## raise PrinterNotReady ## # structure of t: ## # http://msdn.microsoft.com/library/default.asp?\ ## # url=/library/en-us/gdi/prntspol_9otu.asp ## """ ## ('\\\\KYLLIKI', ## '\\\\KYLLIKI\\Samsung ML-1200 Series', ## 'ML-1200', ## 'LPT1:', ## 'Samsung ML-1200 Series', ## 'Samsung ML-1210/ML-1220M', ## '', None, '', 'WinPrint', ## 'RAW', '', None, 24, 1, 0, 0, 0, 0, 1, 0) ## """ ## only on win95: ## try: ## h = win32print.EnumPrinters(win32print.PRINTER_ENUM_DEFAULT) ## except pywintypes.error,e: ## raise PrinterNotReady try: self.dc.StartDoc(self.jobName, self.spoolFile) except win32ui.error, e: raise PrinterNotReady("StartDoc() failed")
def test_ps(printer='MyPSPrinter', filename=r'G:/test.ps', margin=(0.25,1.5,0.25,1.0), font_size=24, text=None): '''render postscript text and graphics to a file''' if text is None: text_data = "This is a test.\nThis is only a test." else: text_data = (text.encode()) # Get the printer's DEVMODE structure h_printer = win32print.OpenPrinter(printer) devmode = win32print.GetPrinter(h_printer, 2)['pDevMode'] win32print.ClosePrinter(h_printer) # set up the device context # see MSDN: ff552837, aa452943, dd319099, dd145045 devmode.FormName = 'Letter' # or 'A4' devmode.PaperSize = win32con.DMPAPER_LETTER # or DMPAPER_A4 devmode.Orientation = win32con.DMORIENT_PORTRAIT devmode.PrintQuality = win32con.DMRES_HIGH devmode.Color = win32con.DMCOLOR_MONOCHROME devmode.TTOption = win32con.DMTT_SUBDEV devmode.Scale = 100 devmode.Fields |= (win32con.DM_FORMNAME | win32con.DM_PAPERSIZE | win32con.DM_ORIENTATION | win32con.DM_PRINTQUALITY | win32con.DM_COLOR | win32con.DM_TTOPTION | win32con.DM_SCALE) h_dc = win32gui.CreateDC('WINSPOOL', printer, devmode) dc = win32ui.CreateDCFromHandle(h_dc) dc.SetMapMode(win32con.MM_TWIPS) # or MM_HIMETRIC (0.01 mm) # begin writing the document dc.StartDoc('Postscript File Print', filename) dc.StartPage() # we need a pen and a font scale = 20 # 72 pt/inch * 20 twip/pt = 1440 inch = 72*scale pen = win32ui.CreatePen(win32con.PS_SOLID, scale, # 1 pt 0) # black dc.SelectObject(pen) font = win32ui.CreateFont({ 'name': 'Times New Roman', 'height': font_size * scale, 'weight': win32con.FW_NORMAL}) dc.SelectObject(font) # output the text x = int(margin[0] * inch) y = -int(margin[1] * inch) width = int((8.5 - margin[0] - margin[2]) * inch) height = int((11.0 - margin[1] - margin[3]) * inch) rect = (x, y, x + width, y - height) dc.DrawText(text_data, rect, win32con.DT_LEFT) if text is None: # draw 8 steps starting at x = 0.25", y = 3" width = inch height = inch for n in range(8): x = n * width + 18*scale y = -n * height - 3*inch dc.MoveTo((x, y)) dc.LineTo((x + width, y)) dc.MoveTo((x + width, y)) dc.LineTo((x + width, y - height)) dc.EndPage() dc.EndDoc()
def printer_watchdog(): # DEFAULT_LOCALE_ENCODING = get_system_encoding() print win32print.EnumPrinters( win32print.PRINTER_ENUM_LOCAL) # get local printers print win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS ) # get printers which other computer shared default_printer_name = win32print.GetDefaultPrinter() printer = win32print.OpenPrinter(default_printer_name) print win32print.GetPrinter(printer) jobs_list = list() total_seconds = 60 * 5 # reset after 60*5 seconds, see 'known issue 2' in this file. sleep_seconds = 10 times = total_seconds / sleep_seconds current_times = 0 while True: jobs = win32print.EnumJobs(printer, 0, 3, 1) # except: pywintypes.error: (1722, 'EnumJobs', 'RPC 服务器不可用。'), ignored this except # 0 is location of first job, # 3 is number of jobs to enumerate, # 1 is job info level, can be 1(win32print.JOB_INFO_1), 2, 3. 3 is reserved, 1 and 2 can NOT get job status, :( if len(jobs) >= 1: for job in jobs: filename = job.get('pDocument') job_id = job.get('JobId', md5(filename).hexdigest()) job_status = job.get('Status', 0) if job_status in [0x00000002, 0x00000004, 0x00000800]: # JOB_STATUS_ERROR """ Refers: https://docs.microsoft.com/en-us/windows/desktop/printdocs/job-info-2 ~\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\WinSDK\Include\WinSpool.h """ print "printer need to be reset, ... " reset_printer() jobs_list = [ ] # make sure there are not same job id in list current_times = 0 print "Current job: ", job_id, job.get('pUserName'), job.get( 'Submitted'), job.get( 'pMachineName'), filename, "[ %d/%d ]" % ( times, current_times + 1) jobs_list.append(job_id) # if any([jid in jobs_list for jid in (jobs[0].get('JobId'), jobs[-1].get('JobId'))]): # current_times += 1 if Counter(jobs_list).most_common(1)[0][1] > 1: current_times += 1 if current_times > times: """ KNOWN ISSUE 2: It will reset when a document sends lots of pages to printer. This script may reset printer before job finished which is not expected. """ print "printer need to be reset, ... " reset_printer() jobs_list = [] # make sure there are not same job id in list current_times = 0 else: jobs_list = [] current_times = 0 print 'looks good, keep watching ...' time.sleep(sleep_seconds)
def main(*args): # check platform # platform is stored in string platform # platform = platform.system() # if(platform == 'Windows'): # print("OS: Windows") # elif(platform == 'Linux'): # print("OS: Linux") # else: # print("OS: iOS") num_args = len(sys.argv) print("Num textblocks: ", ((num_args -7) /5)) if num_args == 7: print("No textblocks") elif (num_args -7 ) % 5 == 0: print("Ok") else: print("Not a valid input") def make_textblock(text, posx, posy, style, size): textblock = TextBlock(text, posx, posy, style, size) return textblock class TextBlock(object): """ store text_field data """ text = "" posx = 0 posy = 0 font_style = "" font_size = 0 def __init__(self, text, posx, posy, font_style, font_size): self.text = text self.posx = int(posx) self.posy = int(posy) self.font_style = font_style self.font_size = int(font_size) font_family = sys.argv[1] img_posx = int(sys.argv[2]) img_posy = int(sys.argv[3]) img_path = sys.argv[4] img_height = int(sys.argv[5]) img_width = int(sys.argv[6]) text_blocks = [] arg_inc = 7 if (num_args == 7): print("No textblocks") else: while(arg_inc<num_args): text_blocks.append(make_textblock(sys.argv[arg_inc], sys.argv[arg_inc+1], sys.argv[arg_inc+2], sys.argv[arg_inc+3], sys.argv[arg_inc+4])) arg_inc = arg_inc + 5 print("Font family: " + font_family) print("img_posx: " , img_posx) print("img_posy: " , img_posy) print("img_path: " + img_path) print("img_height: " , img_height) print("img_width: " , img_width) for text_block in text_blocks: print("Field " + text_block.text + "'s text: " + text_block.text) print("Field " + text_block.text + "'s posx: ", text_block.posx) print("Field " + text_block.text + "'s posy: ", text_block.posy) print("Field " + text_block.text + "'s font style: " + text_block.font_style) print("Field " + text_block.text + "'s font size: ", text_block.font_size) # if you just want to use the default printer, you need # to retrieve its name. printer = win32print.GetDefaultPrinter() print("Printer: " + printer) # open the printer. hprinter = win32print.OpenPrinter(printer) # retrieve default settings. this code does not work on # win95/98, as GetPrinter does not accept two devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] # # Taken from print_desktop.py # Not sure what it does # # dmsize=win32print.DocumentProperties(0, hprinter, printer, None, None, 0) # ## dmDriverExtra should be total size - fixed size # driverextra=dmsize - pywintypes.DEVMODEType().Size ## need a better way to get DEVMODE.dmSize # dm=pywintypes.DEVMODEType(driverextra) # dm.Fields=dm.Fields|win32con.DM_ORIENTATION|win32con.DM_COPIES # dm.Orientation=win32con.DMORIENT_LANDSCAPE # dm.Copies=2 # win32print.DocumentProperties(0, hprinter, printer, dm, dm, win32con.DM_IN_BUFFER|win32con.DM_OUT_BUFFER) # change paper size and orientation # constants are available here: # http://msdn.microsoft.com/library/default.asp? # url=/library/en-us/intl/nls_Paper_Sizes.asp # number 10 envelope is 20 # This doesn't do anything upon inspection # devmode.PaperSize = 333 # devmode.Orientation = 2 # create dc using new settings. # first get the integer hDC value. note that we need the name. hdc = win32gui.CreateDC("WINSPOOL", printer, devmode) printerwidth=win32print.GetDeviceCaps(hdc, win32con.PHYSICALWIDTH) printerheight=win32print.GetDeviceCaps(hdc, win32con.PHYSICALHEIGHT) # next create a PyCDC from the hDC. dc = win32ui.CreateDCFromHandle(hdc) print("Printer length x width:") print(printerwidth) print(printerheight) # now you can set the map mode, etc. and actually print. # you need to set the map mode mainly so you know how # to scale your output. I do everything in points, so setting # the map mode as "twips" works for me. dc.SetMapMode(win32con.MM_TWIPS) # 1440 per inch # here's that scaling I mentioned: scale_factor = 20 # i.e. 20 twips to the point # Variables # font_size = 30 bmp = Image.open (img_path) print("bmp.size[0]") print(bmp.size[0]) print("bmp.size[1]") print(bmp.size[1]) # if bmp.size[0] > bmp.size[1]: # bmp = bmp.rotate (90) # font = win32ui.CreateFont({ # "name": font_family, # "height": int(scale_factor * font_size), # "weight": 1, # }) # 1 inch = scale_factor * 72 # 1 inch = 1440 twips # start the document. the description variable is a string # which will appear in the print queue to identify the job. dc.StartDoc("Nametag printjob") dib = ImageWin.Dib (bmp) # # SAMPLE, EXPLICIT COORDINATE DRAW # 2.40" x 3.90" with 0.12" FEED # # dib.draw (dc.GetHandleOutput (), ( # int(1.39 * scale_factor * 72), # int(.2 * scale_factor * -72), # int(2.39 * scale_factor * 72), # int(1.2 * scale_factor * -72) # )) # dc.TextOut(int(.89 * scale_factor * 72), int(1.3 * scale_factor * -72), "Grant") # dc.TextOut(int(1.89 * scale_factor * 72), int(1.3 * scale_factor * -72), "George") # dc.SelectObject(font_small) # dc.TextOut(int(1.49 * scale_factor * 72), int(1.8 * scale_factor * -72), "Title") # END SAMPLE dib.draw (dc.GetHandleOutput (), ( img_posx, img_posy * -1, img_posx + img_width, (img_posy + img_height) * -1 )) # to draw anything (other than text) you need a pen. # the variables are pen style, pen width and pen color. pen = win32ui.CreatePen(0, int(scale_factor), 0L) # SelectObject is used to apply a pen or font object to a dc. dc.SelectObject(pen) # again with the SelectObject call. # dc.SelectObject(font) for text_block in text_blocks: font = win32ui.CreateFont({ "name": font_family, "height": scale_factor * text_block.font_size, "weight": 1 }) dc.SelectObject(font) print (text_block.text) print (text_block.posx) print (text_block.posy) dc.TextOut(text_block.posx, text_block.posy * -1, text_block.text) # Half Vertical Line # dc.MoveTo((int(1.89 * scale_factor * 72), int(0 *scale_factor * -72))) # dc.LineTo((int(1.89 * scale_factor * 72), int(2.4 * scale_factor* -72))) # # Half Horizontal Line # dc.MoveTo((int(0 * scale_factor * 72), int(1.2 *scale_factor * -72))) # dc.LineTo((int(3.78 * scale_factor * 72), int(1.2 * scale_factor* -72))) # # 1/3 Horizontal Line # dc.MoveTo((int(0 * scale_factor * 72), int(.8 *scale_factor * -72))) # dc.LineTo((int(3.78 * scale_factor * 72), int(.8 * scale_factor* -72))) # # 2/3 Horizontal Line # dc.MoveTo((int(0 * scale_factor * 72), int(1.6 *scale_factor * -72))) # dc.LineTo((int(3.78 * scale_factor * 72), int(1.6 * scale_factor* -72))) # must not forget to tell Windows we're done. dc.EndDoc() dc.DeleteDC()
def getRandomPoem(): size = len(data) r = random.randint(0, size-1) print(data[r]['titleEN'], "/", data[r]['titleKZ'], "\n") print(data[r]['textEN'], "\n\n") with open('poems.json', mode="r", encoding="utf-8") as f: data = json.load(f) for i in range(len(data)): print(i+1, ":", len(data[i]['textRU']) - len(data[i]['textKZ'])) #getRandomPoem() filename = tempfile.mktemp (".txt") open (filename, "w").write ("This is a test") p = win32print.OpenPrinter("OneNote") job = win32print.StartDocPrinter (p, 1, ("test of raw data", None, "RAW")) win32print.StartPagePrinter(p) win32print.WritePrinter(p, "data to print") win32print.EndPagePrinter(p) os.startfile("C:/Users/TestFile.txt", "print")
def on_gumbNatisni_clicked(self, p): if self.tiskalnik == None: self.tiskalnik = win32print.GetDefaultPrinter() p = win32print.OpenPrinter(self.tiskalnik) t = (win32print.GetPrinter(p, 2)["pDevMode"]) dpi = int(t.PrintQuality) if VERBOSE_NACIN: print "Pripravljam sliko za tiskalnik : " + self.tiskalnik nastavitve = ET.ElementTree(file=self._nastavitve).getroot() odmik_desni = int(nastavitve.find("odmiki/odmik_od_desnega_roba").text) odmik_levi = int(nastavitve.find("odmiki/odmik_od_levega_roba").text) visina = int(nastavitve.find("kuverte/visina").text) sirina = int(nastavitve.find("kuverte/sirina").text) velikost_mm = (sirina, visina) pisava_x = nastavitve.find("pisava").text spl = pisava_x.split(" ") pisava_size = font_size_to_pixel(int(spl[len(spl) - 1]), dpi) if pisava_x.rfind(",") != -1: pisava = pisava_x[0:pisava_x.rfind(",")] else: pisava = pisava_x[0:pisava_x.rfind(" ")] velikost_pix = (mm_to_pixel(velikost_mm[0], dpi), mm_to_pixel(velikost_mm[1], dpi)) odmik_desno = mm_to_pixel(odmik_desni, dpi) odmik_spodaj = mm_to_pixel(odmik_levi, dpi) razmik_vrstice = mm_to_pixel(2, dpi) # Priprava besedila p = Printer() u_datalist = [] if self.tiskanje_izbora: print "Tiskanje izbora..." inc = 0 for px in self.seznamUporabnikov: if px[5] == True: pom = {} for inc in range(0, len(self._kljuci)): if self._kljuci[inc] != None: po = self._kljuci[inc] pom[po] = px[inc] pom["pot"] = self.nakljucna_pot() u_datalist.append(pom) if not self.tiskanje_izbora: bes = self.u_data["m_naziv"] + " " + self.u_data[ "m_ime"] + "\n" + self.u_data[ "m_naslov"] + "\n" + "\n" + self.u_data["m_posta"] if self.u_data["m_drzava"] != "": bes + "\n" + self.u_data["m_drzava"] ims = p.narediPNGKuverto(besedilo=bes, pisava=pisava, velikost_pisave=pisava_size, visina=velikost_pix[1], sirina=velikost_pix[0], odmik_desno=odmik_desno, odmik_spodaj=odmik_spodaj, razmik_vrstice=razmik_vrstice, show_crte=self.kuv_show_crte) file_name = self.nakljucna_pot() if VERBOSE_NACIN: print "Shranjujem sliko na lokacijo : " + file_name ims.write_to_png(file_name) else: #tiskanje izobra for pa in u_datalist: bes = pa["m_naziv"] + " " + pa["m_ime"] + "\n" + pa[ "m_naslov"] + "\n" + "\n" + pa["m_posta"] if pa["m_drzava"] != "": bes + "\n" + pa["m_drzava"] ims = p.narediPNGKuverto(besedilo=bes, pisava=pisava, velikost_pisave=pisava_size, visina=velikost_pix[1], sirina=velikost_pix[0], odmik_desno=odmik_desno, odmik_spodaj=odmik_spodaj, razmik_vrstice=razmik_vrstice, show_crte=self.kuv_show_crte) if VERBOSE_NACIN: print "Pisem sliko : " + pa["pot"] ims.write_to_png(pa["pot"]) hDC = win32ui.CreateDC() hDC.CreatePrinterDC(self.tiskalnik) PHYSICALWIDTH = 110 PHYSICALHEIGHT = 111 PHYSICALOFFSETX = PHYSICALWIDTH + 2 PHYSICALOFFSETY = PHYSICALHEIGHT + 2 LOGPIXELSX = 88 LOGPIXELSY = 90 HORZRES = 8 VERTRES = 10 printable_area = hDC.GetDeviceCaps(HORZRES), hDC.GetDeviceCaps(VERTRES) printer_size = hDC.GetDeviceCaps(PHYSICALWIDTH), hDC.GetDeviceCaps( PHYSICALHEIGHT) printer_margins = hDC.GetDeviceCaps( PHYSICALOFFSETX), hDC.GetDeviceCaps(PHYSICALOFFSETY) hDC.StartDoc("Tiskanje nabora slik") if not self.tiskanje_izbora: bmp = Image.open(file_name) if self.rotacija != 0: bmp = bmp.rotate(self.rotacija) hDC.StartPage() dib = ImageWin.Dib(bmp) desna_poravnava = not False negativni_odmik = False odm_levo = 0 if desna_poravnava: odm_levo = (printer_size[0] - bmp.size[0]) x1 = (-1) * int(printer_margins[0]) + odm_levo y1 = (-1) * int((printer_size[1] - printable_area[1]) / 2) x2 = bmp.size[0] + (-1) * int( (printer_size[0] - printable_area[0]) / 2) + odm_levo y2 = bmp.size[1] + (-1) * int( (printer_size[1] - printable_area[1]) / 2) dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2)) hDC.EndPage() else: for slika in u_datalist: bmp = Image.open(slika["pot"]) if self.rotacija != 0: bmp = bmp.rotate(self.rotacija) hDC.StartPage() dib = ImageWin.Dib(bmp) desna_poravnava = not False negativni_odmik = False odm_levo = 0 if desna_poravnava: odm_levo = (printer_size[0] - bmp.size[0]) x1 = (-1) * int(printer_margins[0]) + odm_levo y1 = (-1) * int((printer_size[1] - printable_area[1]) / 2) x2 = bmp.size[0] + (-1) * int( (printer_size[0] - printable_area[0]) / 2) + odm_levo y2 = bmp.size[1] + (-1) * int( (printer_size[1] - printable_area[1]) / 2) dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2)) hDC.EndPage() hDC.EndDoc() hDC.DeleteDC() if VERBOSE_NACIN: print "Konec posiljanja slike v tiskalnik... " if VERBOSE_NACIN: print "Brisanje slik iz temp!" # Brisanje slik iz temp! if self.tiskanje_izbora: for slike in u_datalist: print "Brisem : " + slike["pot"] os.unlink(slike["pot"]) else: print "Brisem : " + file_name os.unlink(file_name)
import win32print, pywintypes, win32con, win32gui, win32api pname = win32print.GetDefaultPrinter() print(pname) p = win32print.OpenPrinter(pname) print('Printer handle: ', p) print_processor = win32print.GetPrinter(p, 2)['pPrintProcessor'] ## call with last parm set to 0 to get total size needed for printer's DEVMODE dmsize = win32print.DocumentProperties(0, p, pname, None, None, 0) ## dmDriverExtra should be total size - fixed size driverextra = dmsize - pywintypes.DEVMODEType( ).Size ## need a better way to get DEVMODE.dmSize dm = pywintypes.DEVMODEType(driverextra) dm.Fields = dm.Fields | win32con.DM_ORIENTATION | win32con.DM_COPIES dm.Orientation = win32con.DMORIENT_LANDSCAPE dm.Copies = 2 win32print.DocumentProperties(0, p, pname, dm, dm, win32con.DM_IN_BUFFER | win32con.DM_OUT_BUFFER) pDC = win32gui.CreateDC(print_processor, pname, dm) printerwidth = win32print.GetDeviceCaps(pDC, win32con.PHYSICALWIDTH) printerheight = win32print.GetDeviceCaps(pDC, win32con.PHYSICALHEIGHT) hwnd = win32gui.GetDesktopWindow() l, t, r, b = win32gui.GetWindowRect(hwnd) desktopheight = b - t desktopwidth = r - l dDC = win32gui.GetWindowDC(hwnd) dcDC = win32gui.CreateCompatibleDC(dDC) dcBM = win32gui.CreateCompatibleBitmap(dDC, desktopwidth, desktopheight)
#!/usr/bin/python # -*- coding: utf-8 -*- # from: http://timgolden.me.uk/python/win32_how_do_i/print.html import os, sys import win32print printer_name = win32print.GetDefaultPrinter () print(printer_name) # # raw_data could equally be raw PCL/PS read from # some print-to-file operation # if sys.version_info >= (3,): raw_data = bytes ("This is a test", "utf-8") else: raw_data = "This is a test" hPrinter = win32print.OpenPrinter (printer_name) try: hJob = win32print.StartDocPrinter (hPrinter, 1, ("2test of raw data to office", None, "RAW")) try: win32print.StartPagePrinter (hPrinter) win32print.WritePrinter (hPrinter, raw_data) win32print.EndPagePrinter (hPrinter) finally: win32print.EndDocPrinter (hPrinter) finally: win32print.ClosePrinter (hPrinter)
def open(self, job_name="python-escpos"): if self.printer_name is None: raise Exception("Printer not found") self.hPrinter = win32print.OpenPrinter(self.printer_name) self.current_job = win32print.StartDocPrinter(self.hPrinter, 1, (job_name, None, "RAW")) win32print.StartPagePrinter(self.hPrinter)
import win32print import win32gui import win32ui import win32con #because we use MM_TWIPS: inch = 1440.0 mm = inch / 25.4 jobName="test" printerName=win32print.GetDefaultPrinter() spoolFile=r"c:\tmp.ps" # open the printer. hprinter = win32print.OpenPrinter(printerName) # retrieve default settings. this code has complications on # win95/98, I'm told, but I haven't tested it there. props = win32print.GetPrinter(hprinter,2) devmode=props["pDevMode"] if devmode is None: # workaround, see http://lino.saffre-rumma.ee/news/477.html print "%r has no pDevMode property" % props else: # change paper size and orientation # constants are available here: # http://msdn.microsoft.com/library/default.asp?\ # url=/library/en-us/intl/nls_Paper_Sizes.asp devmode.PaperSize = win32con.DMPAPER_A4 devmode.Orientation = win32con.DMORIENT_PORTRAIT
def main(argv): inputfile = 'C:/Users/sci/Downloads/cat.jpg' try: opts, args = getopt.getopt(argv, "hi:", ["ifile="]) except getopt.GetoptError: print 'print.py -i <inputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'print.py -i <inputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg print 'Input file is ', inputfile # # Constants for GetDeviceCaps # # # HORZRES / VERTRES = printable area # HORZRES = 8 VERTRES = 10 # # LOGPIXELS = dots per inch # LOGPIXELSX = 88 LOGPIXELSY = 90 # # PHYSICALWIDTH/HEIGHT = total area # PHYSICALWIDTH = 110 PHYSICALHEIGHT = 111 # # PHYSICALOFFSETX/Y = left / top margin # PHYSICALOFFSETX = 112 PHYSICALOFFSETY = 113 printer_name = win32print.GetDefaultPrinter() file_name = inputfile # # You can only write a Device-independent bitmap # directly to a Windows device context; therefore # we need (for ease) to use the Python Imaging # Library to manipulate the image. # # Create a device context from a named printer # and assess the printable size of the paper. # printer = win32print.OpenPrinter( printer_name, {'DesiredAccess': win32print.PRINTER_ALL_ACCESS}) d = win32print.GetPrinter(printer, 2) devmode = d['pDevMode'] #print 'Status ', d['Status'] #for n in dir(devmode): # print "%s\t%s" % (n, getattr(devmode, n)) #if d[18]: #print "Printer not ready" #print ':'.join(x.encode('hex') for x in devmode.DriverData) devmode.PaperLength = 381 devmode.PaperWidth = 381 win32print.SetPrinter(printer, 2, d, 0) ### dmsize=win32print.DocumentProperties(0, printer, printer_name, None, None, 0) ### dmDriverExtra should be total size - fixed size ## driverextra=dmsize - pywintypes.DEVMODEType().Size ## need a better way to get DEVMODE.dmSize ## dm=pywintypes.DEVMODEType(driverextra) ## #win32print.DocumentProperties(0, printer, printer_name, dm, None, win32con.DM_IN_BUFFER) ## #for n in dir(dm): ## # print "%s\t%s" % (n, getattr(dm, n)) ## #dm.Fields=dm.Fields|win32con.DM_ORIENTATION|win32con.DM_COPIES ## #dm.Orientation=win32con.DMORIENT_LANDSCAPE ## #dm.Copies=2 ## #dm.PaperSize = 256 ## #dm.PaperLength = 381 ## #dm.PaperWidth = 381 ## for n in dir(dm): ## print "%s\t%s" % (n, getattr(dm, n)) ## win32print.DocumentProperties(0, printer, printer_name, dm, dm, win32con.DM_IN_BUFFER|win32con.DM_OUT_BUFFER) ## for n in dir(dm): ## print "%s\t%s" % (n, getattr(dm, n)) hDC = win32ui.CreateDC() hDC.CreatePrinterDC(printer_name) printable_area = hDC.GetDeviceCaps(HORZRES), hDC.GetDeviceCaps(VERTRES) printer_size = hDC.GetDeviceCaps(PHYSICALWIDTH), hDC.GetDeviceCaps( PHYSICALHEIGHT) printer_margins = hDC.GetDeviceCaps(PHYSICALOFFSETX), hDC.GetDeviceCaps( PHYSICALOFFSETY) #printable_area = (900, 900) #printer_size = (900, 900) print "printer area", printable_area print "printer size", printer_size print "printer margins", printer_margins # # Open the image, rotate it if it's wider than # it is high, and work out how much to multiply # each pixel by to get it as big as possible on # the page without distorting. # bmp = Image.open(file_name) if bmp.size[0] > bmp.size[1]: bmp = bmp.rotate(90) print "bmp size", bmp.size ratios = [ 1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1] ] scale = min(ratios) scaled_width, scaled_height = [int(scale * i) for i in bmp.size] x1 = int((printer_size[0] - scaled_width) / 2) y1 = int((printer_size[1] - scaled_height) / 2) x2 = x1 + scaled_width y2 = y1 + scaled_height print "print rect: ", x1, y1, x2, y2 #sys.exit() # # Start the print job, and draw the bitmap to # the printer device at the scaled size. # try: hDC.StartDoc(file_name) hDC.StartPage() dib = ImageWin.Dib(bmp) dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2)) hDC.EndPage() hDC.EndDoc() hDC.DeleteDC() except win32ui.error as e: print "Unexpected error:", e
#KwickPython [FREE TO USE, NO WARRANTY] #link back to https://kwickpos.com import cgi,os,sys,win32print,pywintypes print("Access-Control-Allow-Origin: *") print("Content-Type: text/plain\n") form = cgi.FieldStorage() p=form.getvalue('p') if p: data=form.getvalue('data') if data: import base64 raw_data=base64.b64decode(data) if raw_data: h = win32print.OpenPrinter(p) hJob = win32print.StartDocPrinter (h, 1, ("KwickPOS Ticket", None, "RAW")) win32print.StartPagePrinter (h) b=win32print.WritePrinter (h, raw_data) win32print.EndPagePrinter (h) win32print.EndDocPrinter (h) win32print.ClosePrinter (h) print(b) sys.exit() else: try: h = win32print.OpenPrinter(p) d = win32print.GetPrinter(h,2) win32print.ClosePrinter (h) a = d['Attributes'] hex=hex(a) if ( hex[-3] == '6' ): print(p+' Offline')
def print_receipt(ip_dic, user_dic): import win32ui, win32con, win32gui, win32print, traceback tarihsaat = strftime("%d/%m/%Y %H:%M:%S") active_orders = user_dic['table{}'.format( ip_dic[request.remote_addr][0])]['orders'] yazi = 'Table {}\n\n{}\n\n\n'.format(ip_dic[request.remote_addr][0], tarihsaat) toplam_y = 0 iskonto_kontrol = 0 for item in active_orders: if item[0] == 'Discount': iskonto_kontrol = 1 if iskonto_kontrol == 1: for item in active_orders[1:-1]: yazi = yazi + """{0} {1} x {2} TL ={3} TL\n""".format( str(item[0]), str(item[1]), str(item[2]), str( item[1] * item[2])) toplam_y = toplam_y + item[1] * item[2] yazi = yazi + "\nTotal: {} TL\n".format(toplam_y) yazi = yazi + "Discount: {} TL\n".format( -active_orders[-1][1] * active_orders[-1][2]) yazi = yazi + "Hesap: {} TL\n".format(toplam_y + (active_orders[-1][1] * active_orders[-1][2])) else: for item in active_orders[1:]: yazi = yazi + """{0} {1} x {2} TL ={3} TL\n""".format( str(item[0]), str(item[1]), str(item[2]), str( item[1] * item[2])) toplam_y = toplam_y + item[1] * item[2] yazi = yazi + "\nTotal: {} TL\n".format(toplam_y) yazi = yazi + "\nMali değeri yoktur.\n" # init, bla bla bla printername = win32print.GetDefaultPrinter() hprinter = win32print.OpenPrinter(printername) # load default settings devmode = win32print.GetPrinter(hprinter, 8)["pDevMode"] # this is where it gets INTERESTING: # after the following two lines, use: # dc for win32ui calls like LineTo, SelectObject, ... # hdc for DrawTextW, your *MAGIC* function that supports unicode output hdc = win32gui.CreateDC("WINSPOOL", printername, devmode) dc = win32ui.CreateDCFromHandle(hdc) # 1440 twips = 1 inch dc.SetMapMode(win32con.MM_TWIPS) # 20 twips = 1 pt scale_factor = 20 # start the document, description as unicode description = u'Test1' dc.StartDoc(description) # when working with the printer, enclose any potentially failing calls within a try block, # because if you do not properly end the print job (see bottom), after a couple of such failures, # you might need to restart windows as it runs out of handles or something and starts # behaving in an unpredictable way, some documents fail to print, you cannot open windows, etc. try: # Use a font font = win32ui.CreateFont({ "name": "Arial Unicode MS", # a font name "height": int(scale_factor * 14), # 14 pt "weight": 400, # 400 = normal }) # use dc -- SelectObject is a win32ui call dc.SelectObject(font) # this is the miracle where the unicode text gets to be printed; notice hdc, # not dc, for DrawTextW uses a different handle, i have found this in other posts win32gui.DrawTextW(hdc, yazi, -1, (0, 0, 4000, -12000), win32con.DT_CENTER) except: traceback.print_exc() # must not forget to tell Windows we're done. This line must get called if StartDoc # was called, if you fail to do so, your sys might start behaving unexpectedly dc.EndDoc()
def list_jobs(): p_handle = win32print.OpenPrinter(PRINTER_NAME) # printer handler print_jobs = win32print.EnumJobs(p_handle, 0, -1, 1) return print_jobs
import win32api import win32print printer_name = win32print.GetDefaultPrinter() print("默认打印机", printer_name) handle_printer = win32print.OpenPrinter(printer_name) # 获取打印机句柄 printer_info = win32print.GetPrinter(handle_printer, 2) # 调用相关函数进行信息查询 for k in printer_info: print(k, printer_info[k]) task_list = win32print.EnumJobs(handle_printer, 0, 10) # 参数(句柄,编文档号,枚举条数) print(task_list) import bin.my_lib.data_sqlite as db res = db.execute('SELECT * FROM KEY_VALUE') print('res:', res)