標籤:
1 # -*- coding:utf-8 -*- 2 # Author: Pete Yim<[email protected]> 3 # Date : 13-8-22 4 # Copyright (c) 2013 RCSH Systems Incorporated. All rights reserved. 5 import win32print 6 import win32ui 7 from PIL import Image, ImageWin 8 import _imaging 9 10 #11 # Constants for GetDeviceCaps12 #13 #14 # HORZRES / VERTRES = printable area15 #16 HORZRES = 817 VERTRES = 1018 #19 # LOGPIXELS = dots per inch20 #21 LOGPIXELSX = 8822 LOGPIXELSY = 9023 #24 # PHYSICALWIDTH/HEIGHT = total area25 #26 PHYSICALWIDTH = 11027 PHYSICALHEIGHT = 11128 #29 # PHYSICALOFFSETX/Y = left / top margin30 #31 PHYSICALOFFSETX = 11232 PHYSICALOFFSETY = 11333 34 printer_name = win32print.GetDefaultPrinter ()35 file_name = "E:\\abc.jpg"36 37 #38 # You can only write a Device-independent bitmap39 # directly to a Windows device context; therefore40 # we need (for ease) to use the Python Imaging41 # Library to manipulate the image.42 #43 # Create a device context from a named printer44 # and assess the printable size of the paper.45 #46 hDC = win32ui.CreateDC ()47 hDC.CreatePrinterDC (printer_name)48 printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)49 printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)50 printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)51 52 #53 # Open the image, rotate it if it‘s wider than54 # it is high, and work out how much to multiply55 # each pixel by to get it as big as possible on56 # the page without distorting.57 #58 bmp = Image.open (file_name)59 if bmp.size[0] > bmp.size[1]:60 bmp = bmp.rotate (90)61 62 ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]63 scale = min (ratios)64 65 #66 # Start the print job, and draw the bitmap to67 # the printer device at the scaled size.68 #69 hDC.StartDoc (file_name)70 hDC.StartPage ()71 72 dib = ImageWin.Dib (bmp)73 scaled_width, scaled_height = [int (scale * i) for i in bmp.size]74 x1 = int ((printer_size[0] - scaled_width) / 2)75 y1 = int ((printer_size[1] - scaled_height) / 2)76 x2 = x1 + scaled_width77 y2 = y1 + scaled_height78 dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))79 80 hDC.EndPage ()81 hDC.EndDoc ()82 hDC.DeleteDC ()
註:python調用win32介面列印照片
Python win32列印樣本