def printImage(printer_name, bmp, paperSize=win32con.DMPAPER_A4, tray=None, jobTitle="Untitled"): """ Функция печати изображения по входным параметрам: :param printer_name: имя принтера в windows :param img: :param paperSize: :param tray: пример использования печати на принтере по-умолчанию на формате А4. Источник бумаги - лоток А4 printImage(win32print.GetDefaultPrinter(),filename,win32con.DMPAPER_A4,XEROX_A4_TRAY) """ PRINTER_DEFAULTS = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} hprinter = win32print.OpenPrinter(printer_name, PRINTER_DEFAULTS) properties = win32print.GetPrinter(hprinter, 2) pr = properties['pDevMode'] if paperSize == win32con.DMPAPER_A2: pr.Orientation = win32con.DMORIENT_LANDSCAPE pr.PaperSize = paperSize if tray: pr.DefaultSource = tray properties['pDevMode'] = pr try: win32print.SetPrinter(hprinter, 2, properties, 0) except pywintypes.error, err: logger.error(err[2].decode('cp1251').encode('utf-8')) sys.exit()
def init_printer(): name = win32print.GetDefaultPrinter() print "printer name: " + name # printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_ADMINISTER} printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE} handle = win32print.OpenPrinter(name, printdefaults) level = 2 attributes = win32print.GetPrinter(handle, level) print "Old Duplex = %d" % attributes['pDevMode'].Duplex # attributes['pDevMode'].Duplex = 1 # no flip attributes['pDevMode'].Duplex = 2 # flip up # attributes['pDevMode'].Duplex = 3 # flip over ## 'SetPrinter' fails because of 'Access is denied.' ## But the attribute 'Duplex' is set correctly try: win32print.SetPrinter(handle, level, attributes, 0) except: print "win32print.SetPrinter: set 'Duplex'" return name, printdefaults, handle, attributes
def ImprimirArquivo(numeroPedido, event=None): #Função para Imprimir o Pedido try: # Definindo o caminho do arquivo para impressão arquivo = "C:/Users/Itamar/Documents/GitHub/Sistema-Scripts/pedidos/Pedido" + str( numeroPedido) + '.txt' _printer = StringVar(Pedidos_window) # Setando a impressora padrão do windows _printer.set(win32print.GetDefaultPrinter()) #print(_printer) PRINTER_DEFAULTS = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter(_printer.get(), PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) win32print.SetPrinter(pHandle, 2, properties, 0) try: #win32print.SetDefaultPrinter(_printer.get()) win32api.ShellExecute(0, "print", arquivo, None, ".", 0) win32print.ClosePrinter(pHandle) except: pass messagebox.showerror("Error", "Não foi passivel imprimir o pedido.") except: pass messagebox.showerror("Error", "Não foi passivel imprimir o pedido.")
def printPdf(selPrt, pdfFN, paperForm, numCopies): #Save the current default Printer dfltPrt = win32print.GetDefaultPrinter() win32print.SetDefaultPrinter(selPrt) #reportStat('====>> DefaultPrinter: {}'.format( win32print.GetDefaultPrinter()), None) handle, level, prtProperties = prepPrinter(selPrt) setXeroxAttr(prtProperties, paperForm, numCopies) #createDC(dfltPrt, prtProperties['pDevMode']) ## 'SetPrinter' fails because of 'Access is denied.' ## But the attribute 'Duplex' is set correctly #try: win32print.SetPrinter(handle, level, prtProperties, 0) #except: # #reportStat("win32print.SetPrinter: set 'Duplex'", None) # pass #cfgPrt(selPrt) res = win32api.ShellExecute(0, 'print', pdfFN, None, '.', 0) win32print.ClosePrinter(handle) handle, level, prtProperties = prepPrinter(selPrt) showpDevMode(prtProperties) #Restore the current default Printer win32print.SetDefaultPrinter(dfltPrt)
def StartPrint (printer='MyPSPrinter', path=r'D:\test.txt', copies = 1, orientation = win32con.DMORIENT_PORTRAIT, duplex = win32con.DMDUP_HORIZONTAL, printQuality = win32con.DMRES_HIGH, color = win32con.DMCOLOR_MONOCHROME, paperSize = win32con.DMPAPER_LETTER, # or DMPAPER_A4 text=None): PRINTER_DEFAULTS = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} h_printer = win32print.OpenPrinter(printer, PRINTER_DEFAULTS) properties = win32print.GetPrinter(h_printer, 2) devmode = properties["pDevMode"] devmode.FormName = 'A4' # or 'Letter' devmode.PaperSize = paperSize devmode.Orientation = orientation devmode.PrintQuality = printQuality devmode.Color = color devmode.TTOption = win32con.DMTT_SUBDEV devmode.Scale = 100 devmode.Copies = copies devmode.Duplex =duplex devmode.Fields |= (win32con.DM_FORMNAME | win32con.DM_PAPERSIZE | win32con.DM_ORIENTATION | win32con.DM_PRINTQUALITY | win32con.DM_COLOR | win32con.DM_TTOPTION | win32con.DM_SCALE) properties['pDevMode'] =devmode win32print.SetPrinter(h_printer, 2, properties, 0) win32print.SetDefaultPrinter(printer) try: listOfFiles = os.listdir(path) if (len(listOfFiles)!=0): for file in listOfFiles: filename = path+'\\'+file print(filename) print(win32api.ShellExecute( 0, "printto", filename, '"%s"' % win32print.GetDefaultPrinter(), ".", 0 )) print_jobs = win32print.EnumJobs(h_printer, 0, -1, 2) delete = True while (delete): old_print_jobs = print_jobs print_jobs = win32print.EnumJobs(h_printer, 0, -1, 2) if((len(print_jobs) == 0) & (len(old_print_jobs)!=0)): print('ok') delete = False filename = path+'\\'+file os.remove(filename) except FileNotFoundError: print('Directory not created.')
def enable_printers(): data = get_printers() for tup in data: handle = win32print.OpenPrinter(tup[2], {"DesiredAccess": win32print.PRINTER_ALL_ACCESS}) try: win32print.SetPrinter(handle, 0, win32print.PRINTER_STATUS_WAITING, win32print.PRINTER_CONTROL_SET_STATUS) except Exception as e: print(e)
def set_duplex(printer_no, duplex): print_defaults = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} handle = win32print.OpenPrinter(app_config.PRINTER_NAMES[printer_no], print_defaults) level = 2 attributes = win32print.GetPrinter(handle, level) attributes['pDevMode'].Duplex = duplex try: win32print.SetPrinter(handle, level, attributes, 0) except Exception as e: print('Failed to set duplex') print(e) finally: win32print.ClosePrinter(handle)
def prepPrt(): # Setting paper tray PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter('RICOH-LOCAL', PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) #get the properties pDevModeObj = properties["pDevMode"] #get the devmode tray_one = 1 tray_two = 3 tray_three = 2 printer_tray = [] automaticTray = 7 pDevModeObj.DefaultSource = tray_two #set the tray properties["pDevMode"]=pDevModeObj #write the devmode back to properties win32print.SetPrinter(pHandle,2,properties,0) #save the properties to the printer
def printPdf(selPrt, pdfFN, paperForm, numCopies): #Save the current default Printer dfltPrt = win32print.GetDefaultPrinter() win32print.SetDefaultPrinter(selPrt) #reportStat('====>> DefaultPrinter: {}'.format( win32print.GetDefaultPrinter()), None) handle, level, prtProperties = prepPrinter(selPrt) setXeroxAttr(prtProperties, paperForm, numCopies) win32print.SetPrinter(handle, level, prtProperties, 0) res = win32api.ShellExecute(0, 'print', pdfFN, None, '.', 0) win32print.ClosePrinter(handle) handle, level, prtProperties = prepPrinter(selPrt) #showpDevMode(prtProperties) #Restore the current default Printer win32print.SetDefaultPrinter(dfltPrt)
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(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
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