def prepPrt2(): #http://newcenturycomputers.net/projects/pythonicwindowsprinting.html # if you just want to use the default printer, you need # to retrieve its name. printer = win32print.GetDefaultPrinter() # 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"] # 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 = 20 # 1 = portrait, 2 = landscape 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) # next create a PyCDC from the hDC. dc = win32ui.CreateDCFromHandle(hdc)
def createDC(printer, devmode): # create dc using new settings. # first get the integer hDC value. note that we need the name. hdc = win32gui.CreateDC("WINSPOOL", printer, devmode) # next create a PyCDC from the hDC. dc = win32ui.CreateDCFromHandle(hdc)
def screenshot(hwnd=None, title=None): if hwnd is None and title is not None: hwnd = find_window(title) #rect = app[3] dc = win32gui.CreateDC('DISPLAY', None, None) left, top, right, bottom = win32gui.GetWindowRect(hwnd) width = right - left height = bottom - top #user32 = ctypes.windll.LoadLibrary("C:\\Windows\\System32\\user32.dll") hwindc = win32gui.GetWindowDC(hwnd) srcdc = win32ui.CreateDCFromHandle(hwindc) #用dc来获取全屏的截图 memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (0, 0), win32con.SRCCOPY) # #user32.PrintWindow(hwnd, memdc.GetSafeHdc(), 0) bmpinfo = bmp.GetInfo() bmpInt = bmp.GetBitmapBits(False) bmpInt = np.array(bmpInt, dtype=np.uint8).reshape(height, width, 4) return bmpInt, width, height
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: devmode.PaperSize = paper_sizes[self.papersize] if self.orientation is not None: devmode.Orientation = orientations[self.orientation] # 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.StartDoc(desc) self.pen = win32ui.CreatePen(0, int(scale_factor), 0L) self.dc.SelectObject(self.pen) self.page = 1
def cfgPrt(selPrt): p = win32print.OpenPrinter(selPrt) printprocessor = win32print.GetPrinter(p, 2)['pPrintProcessor'] dmsize = win32print.DocumentProperties(0, p, selPrt, None, None, 0) driverextra = dmsize - pywintypes.DEVMODEType().Size dm = pywintypes.DEVMODEType(driverextra) dm.Fields = dm.Fields | win32con.DM_ORIENTATION | win32con.DM_COPIES #|win32con.DM_PAPERSIZE dm.Orientation = win32con.DMORIENT_LANDSCAPE dm.Copies = 1 #dm.Papersize=win32con.DM_PAPERLENGTH(790) #dm.Paperwidth=530 win32print.DocumentProperties( 0, p, selPrt, dm, dm, win32con.DM_IN_BUFFER | win32con.DM_OUT_BUFFER) hDC = win32gui.CreateDC(printprocessor, selPrt, dm) printerwidth = win32ui.GetDeviceCaps(hDC, 110) printerheight = win32ui.GetDeviceCaps(hDC, 111)
def _take_screenshot_with_native_api(self, x, y, w, h, hwnd): if hwnd is None: scr_hdc = win32gui.CreateDC('DISPLAY', None, None) else: scr_hdc = win32gui.GetDC(hwnd) mem_hdc = win32gui.CreateCompatibleDC(scr_hdc) new_bitmap_h = win32gui.CreateCompatibleBitmap(scr_hdc, w, h) win32gui.SelectObject( mem_hdc, new_bitmap_h ) # Returns 'old_bitmap_h'. It will be deleted automatically. win32gui.BitBlt(mem_hdc, 0, 0, w, h, scr_hdc, x, y, win32con.SRCCOPY) bmp = win32ui.CreateBitmapFromHandle(new_bitmap_h) bmp_info = bmp.GetInfo() if bmp_info['bmHeight'] != h or bmp_info['bmWidth'] != w: raise FailExit('bmp_info = {bmp}, but (w, h) = ({w}, {h})'.format( bmp=bmp_info, width=w, height=h)) if bmp_info['bmType'] != 0 or bmp_info['bmPlanes'] != 1: raise FailExit( 'bmp_info = {bmp}: bmType !=0 or bmPlanes != 1'.format( bmp=str(bmp_info))) if bmp_info['bmBitsPixel'] % 8 != 0: raise FailExit( 'bmp_info = {bmp}: bmBitsPixel mod. 8 is not zero'.format( bmp=str(bmp_info))) bmp_arr = list(bmp.GetBitmapBits()) if len(bmp_arr) == w * h * 4: del bmp_arr[3:: 4] # Delete alpha channel. TODO: Is it fast enough??? elif len(bmp_arr) != w * h * 3: raise FailExit('An error occurred while read bitmap bits') result = np.array(bmp_arr, dtype=np.uint8).reshape((h, w, 3)) win32gui.DeleteDC(mem_hdc) win32gui.DeleteObject(new_bitmap_h) if not hwnd: win32gui.DeleteDC(scr_hdc) else: win32gui.ReleaseDC(hwnd, scr_hdc) return result
def SetPrinter(self, printer, isPortrait): self.printer_name = printer # self.printer_name = 'Microsoft Print to PDF' # self.printer_name = 'HP LaserJet MFP M28-M31 PCLm-S (Network)' self.device = win32print.OpenPrinter(printer) self.devmode = win32print.GetPrinter(self.device, 2)["pDevMode"] print('paper size:', self.devmode.PaperSize) # http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html # 1 = portrait, 2 = landscape self.devmode.Orientation = 1 if isPortrait else 2 self.devmode.PaperSize = 10 # A4 = 10 # self.devmode.PaperLength = 4 # self.devmode.PaperWidth = 4 self.hdc = win32gui.CreateDC("WINSPOOL", self.printer_name, self.devmode) self.dc = win32ui.CreateDCFromHandle(self.hdc)
def do_print_qu(): str1=current_textarea.get("0.0","end") pname=win32print.GetDefaultPrinter() pHandle=win32print.OpenPrinter(pname) printinfo=win32print.GetPrinter(pHandle,2) pDevModeObj=printinfo["pDevMode"] pDevModeObj.Scale=100 DC=win32gui.CreateDC("WINSPOOL",pname,pDevModeObj) hDC= win32ui.CreateDCFromHandle(DC) hDC.StartDoc("Python Editor") hDC.StartPage() hDC.TextOut(20,20,str1) hDC.EndPage() hDC.EndDoc() win32gui.DeleteDC(DC)
def get_color(pos): hdc_screen = win32gui.CreateDC("DISPLAY", "", None) hmem_dc = win32gui.CreateCompatibleDC(hdc_screen) h_bitmap = win32gui.CreateCompatibleBitmap(hdc_screen, 1, 1) h_old_bitmap = win32gui.SelectObject(hmem_dc, h_bitmap) win32gui.BitBlt(hmem_dc, 0, 0, 1, 1, hdc_screen, pos[0], pos[1], win32con.SRCCOPY) win32gui.DeleteDC(hdc_screen) win32gui.DeleteDC(hmem_dc) x = win32ui.CreateBitmapFromHandle(h_bitmap) bits = x.GetBitmapBits(True) return struct.unpack('I', bits)[0]
def getMonitorProfile(cls, qscreen=None): """ Try to retrieve the default color profile associated to the monitor specified by QScreen (the system main display if qscreen is None). The method returns None if no profile can be found. @param qscreen: QScreen instance @type qscreen: QScreen @return: monitor profile @rtype: CmsProfile """ # from PIL.ImageWin import HDC try: if qscreen is not None and sys.platform == 'win32': dc = win32gui.CreateDC(str(qscreen.name()), None, None) monitorProfile = cls.B_get_display_profile(dc) else: monitorProfile = cls.B_get_display_profile() except (RuntimeError, OSError, TypeError): monitorProfile = None return monitorProfile
def OnInit(self): dll = ctypes.WinDLL('gdi32.dll') for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)): hDeskDC = win32gui.CreateDC(win32api.GetMonitorInfo(hMon)['Device'], None, None) bitmap = wx.Bitmap(right - left, bottom - top) hMemDC = wx.MemoryDC() hMemDC.SelectObject(bitmap) try: dll.BitBlt(hMemDC.GetHDC(), 0, 0, right - left, bottom - top, int(hDeskDC), 0, 0, win32con.SRCCOPY) finally: hMemDC.SelectObject(wx.NullBitmap) bitmap.SaveFile('screenshots/screenshot_%02d.bmp' % idx, wx.BITMAP_TYPE_BMP) win32gui.ReleaseDC(win32gui.GetDesktopWindow(), hDeskDC) im1 = Image.open('screenshots/screenshot_00.bmp', 'r') for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)): if idx == 0: continue im2 = Image.open('screenshots/screenshot_%02d.bmp' % idx, 'r') im1 = get_concat_h(im1, im2) im1.save('screenshots/screenshot.jpg') return True
def _on_mouse_move(self, hwnd, message, wparam, lparam): """Mouse moving event""" # get current mouse coordinates x, y = win32api.GetCursorPos() if self._drag: hdc = win32gui.CreateDC("DISPLAY", None, None) pycdc = win32ui.CreateDCFromHandle(hdc) pycdc.SetROP2(win32con.R2_NOTXORPEN) # erase old rectangle if self._draw: win32gui.Rectangle(hdc, self._start[0], self._start[1], self._end[0], self._end[1]) # draw new rectangle self._draw = True win32gui.Rectangle(hdc, self._start[0], self._start[1], x, y) self._end = (x, y)
def getMonitorProfile(cls, qscreen=None): """ Try to retrieve the default color profile associated to the monitor specified by QScreen (the system main display if qscreen is None). The method returns None if no profile can be found. @param qscreen: QScreen instance @type qscreen: QScreen @return: monitor profile @rtype: CmsProfile """ try: if qscreen is not None and sys.platform == 'win32': dc = win32gui.CreateDC(qscreen.name(), None, None) monitorProfile = get_display_profile( dc) # cf. imageCms.get_display_profile_win32 v5.1.0 patch else: monitorProfile = get_display_profile() except (RuntimeError, OSError): monitorProfile = None return monitorProfile
def prepPrtTray(): # Constants from wingdi.h DM_OUT_BUFFER = 0x02 DM_IN_BUFFER = 0x08 DM_IN_PROMPT = 0x04 DM_DEFAULT_SOURCE = 0x200 # Get a handle for the default printer device_name = win32print.GetDefaultPrinter() handle = win32print.OpenPrinter(device_name) # Get the default properties for the printer properties = win32print.GetPrinter(handle, 2) devmode = properties['pDevMode'] # Print the default paper source (prints '7' for 'Automatically select') print(devmode.DefaultSource) # Change the default paper source to '4' for 'Manual feed' devmode.DefaultSource = 4 devmode.Fields = devmode.Fields | DM_DEFAULT_SOURCE # Write these changes back to the printer win32print.DocumentProperties(None, handle, device_name, devmode, devmode, DM_IN_BUFFER | DM_OUT_BUFFER) # Confirm the changes were updated print(devmode.DefaultSource) # Aaargh! Prints '7' again! # Start printing with the device hdc = win32gui.CreateDC('', device_name, devmode) win32print.StartDoc(hdc, ('Test', None, None, 0)) win32print.StartPage(hdc) # ... GDI drawing commands ... win32print.EndPage(hdc) win32print.EndDoc(hdc)
def _on_mouse_up(self, hwnd, message, wparam, lparam): """Mouse up event""" if self._draw: # cleanup rectangle on desktop self._drag = False self._draw = False hdc = win32gui.CreateDC("DISPLAY", None, None) pycdc = win32ui.CreateDCFromHandle(hdc) pycdc.SetROP2(win32con.R2_NOTXORPEN) win32gui.Rectangle(hdc, self._start[0], self._start[1], self._end[0], self._end[1]) # save bitmap capture_screen(self._filename, self._start[0], self._start[1], self._end[0], self._end[1]) self.close() if self._shot_callback: self._shot_callback()
def getMonitorProfile(cls, qscreen=None): """ Try to retrieve the default color profile associated to the monitor specified by QScreen (the system main display if qscreen is None). The method returns None if no profile can be found. @param qscreen: QScreen instance @type qscreen: QScreen @return: monitor profile or None @rtype: CmsProfile or None """ monitorProfile = None # detecting profile if qscreen is not None: try: if sys.platform == 'win32': dc = win32gui.CreateDC(str(qscreen.name()), None, None) monitorProfile = cls.B_get_display_profile(handle=dc) else: monitorProfile = cls.B_get_display_profile( device_id=qscreen.name()) except (RuntimeError, OSError, TypeError): pass return monitorProfile
def _thread_function(x, y, w, h, delay): [x, y, w, h] = map(int, [x, y, w, h]) delay = float(delay) # Получим контекст всех дисплев или всего рабочего стола: #scr_hdc = win32gui.GetDC(0) scr_hdc = win32gui.CreateDC('DISPLAY', None, None) mem_hdc = win32gui.CreateCompatibleDC( scr_hdc ) # New context of memory device. This one is compatible with 'scr_hdc' new_bitmap_h = win32gui.CreateCompatibleBitmap(scr_hdc, w + 2, h + 2) win32gui.SelectObject( mem_hdc, new_bitmap_h ) # Returns 'old_bitmap_h'. It will be deleted automatically. # Сохраняем рамочку в 1 пиксель (она вокруг области (x,y,w,h)): _cp_boundary(mem_hdc, 0, 0, scr_hdc, x - 1, y - 1, w + 2, h + 2) # Рисуем подсветку области: # brush = win32gui.CreateSolidBrush(win32api.RGB(255,0,0)) win32gui.SelectObject(scr_hdc, win32gui.GetStockObject(win32con.NULL_BRUSH)) pen = win32gui.CreatePen(win32con.PS_DOT, 1, win32api.RGB(148, 0, 0)) win32gui.SelectObject(scr_hdc, pen) for i in range(2): win32gui.Rectangle(scr_hdc, x - 1, y - 1, x + w + 1, y + h + 1) # Восстаналиваема рамочку: time.sleep(delay) _cp_boundary(scr_hdc, x - 1, y - 1, mem_hdc, 0, 0, w + 2, h + 2) #win32gui.ReleaseDC(scr_hdc, 0) win32gui.DeleteDC(scr_hdc) win32gui.DeleteDC(mem_hdc) win32gui.DeleteObject(new_bitmap_h)
import win32api import win32con import win32gui import win32ui # Get type PyCDC _hwDC = win32gui.CreateDC("DISPLAY", None, None) _DC = win32ui.CreateDCFromHandle(_hwDC) T_PyCDC = type(_DC) _DC.DeleteDC() del _hwDC, _DC
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() # # 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. # gDC = win32gui.CreateDC("WINSPOOL", printer_name, pr) hDC = win32ui.CreateDCFromHandle(gDC) printable_area = hDC.GetDeviceCaps(HORZRES), hDC.GetDeviceCaps(VERTRES) printer_size = hDC.GetDeviceCaps(PHYSICALWIDTH), hDC.GetDeviceCaps( PHYSICALHEIGHT) printer_margins = hDC.GetDeviceCaps(PHYSICALOFFSETX), hDC.GetDeviceCaps( PHYSICALOFFSETY) # # 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. # if ((bmp.size[1] < bmp.size[0]
# Get the default properties for the printer properties = win32print.GetPrinter(printer, 2) devmode = properties['pDevMode'] # Change the default paper source to '4' for 'Manual feed' devmode.DefaultSource = 1 devmode.Fields = devmode.Fields | DM_DEFAULT_SOURCE # Write these changes back to the printer win32print.DocumentProperties(None, printer, device_name, devmode, devmode, DM_IN_BUFFER | DM_OUT_BUFFER) file_name = 'Hello World'.encode() # Start printing with the device hdc = win32gui.CreateDC('', device_name, devmode) hJob = win32print.StartDocPrinter (printer, 1, ("RVGI Print", None, "RAW")) g=open('Test.txt','r') raw_data = (open(r'Test.txt').read()).encode() try: win32print.StartPagePrinter (printer) win32print.WritePrinter (printer, raw_data) win32print.EndPagePrinter (printer) finally: win32print.EndDocPrinter (printer) win32print.ClosePrinter (printer)
story.h2("Windows Default Printer (%s)" % printerName) story.par("GetPrinter()['pDevMode']:") h=win32print.OpenPrinter(printerName) d=win32print.GetPrinter(h,2) devmode=d['pDevMode'] l=[ "%r\t%r\n" % (n,getattr(devmode,n)) for n in dir(devmode) if n != 'DriverData' and n[0]!='_'] ul=story.ul(*l) story.par("EnumFontFamilies:") hprinter = win32print.OpenPrinter(printerName) devmode = win32print.GetPrinter(hprinter,2)["pDevMode"] hdc=win32gui.CreateDC('WINSPOOL',printerName,devmode) l=[] def callback(font, tm, fonttype, param): t="" if fonttype & win32con.DEVICE_FONTTYPE: t+="D" else: t+="d" if fonttype & win32con.RASTER_FONTTYPE: t+="R" else: t+="r" if fonttype & win32con.TRUETYPE_FONTTYPE: t+="T" else:
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 # create dc using new settings. # first get the integer hDC value. # note that we need the name. dch = win32gui.CreateDC("WINSPOOL", printerName, devmode) # next create a PyCDC from the hDC. dc = win32ui.CreateDCFromHandle(dch) dc.StartDoc(jobName,spoolFile) dc.StartPage() from lino.textprinter import devcaps print "LOGPIXELSX",dc.GetDeviceCaps(devcaps.LOGPIXELSX) print "LOGPIXELSY",dc.GetDeviceCaps(devcaps.LOGPIXELSY) devicex = dc.GetDeviceCaps(devcaps.LOGPIXELSX) devicey = dc.GetDeviceCaps(devcaps.LOGPIXELSY)
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) win32gui.SelectObject(dcDC, dcBM) win32gui.StretchBlt(dcDC, 0, 0, desktopwidth, desktopheight, dDC, 0, 0, desktopwidth, desktopheight, win32con.SRCCOPY)
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 get_color(pos=(1656, 923)): #50175 25731 57855 hdc_screen = win32gui.CreateDC("DISPLAY", "", None) return win32gui.GetPixel(hdc_screen, *pos)
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 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 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 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 ()
# 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 # devmode.FormName=u'a5' # 1 = portrait, 2 = landscape devmode.Orientation = 1 # create dc using new settings. # first get the integer hDC value. note that we need the name. hdc = win32gui.CreateDC("WINSPOOL", 'HP Deskjet 2540 series (sieć)', devmode) # hdc = win32gui.CreateDC("WINSPOOL", 'Microsoft Print to PDF', devmode) # next create a PyCDC from the hDC. dc = win32ui.CreateDCFromHandle(hdc) dc.StartDoc('My Document') # dc.StartDoc('My Document', 'c:\\Users\\marci\\Documents\\abc.pdf ') dc.StartPage() max_length = 0 for item in interface.shopping_list: length = dc.GetTextExtent(f'{item.name} {item.amount}\t')[0] if length > max_length: max_length = length max_length += 100