1、Python调用Windows命令打印文件
Windows命令行打印文件使用print 命令,具体用法可使用help print查看。下面是使用Python调用print指令执行打印文件功能的代码:
import os def printer(filename): printername = r"/D://A340/hpLaser" cmd = "print " + printername + " " + filename print "print cmd:", cmd if not os.system(cmd): print "printing..." else: print "some error occurs."if __name__ == "__main__": filename = raw_input("Please input your filename:/n") printer(filename)
这里的打印机用的是共享打印机,所以需要指定域名和打印机名称,而且"/D:"表示的是打印设备的意思。
2、windows下如何用python控制打印机打印
参考网站
首先下载python需要的库
pip install pypiwin32
简单例子
import tempfileimport win32apiimport win32printfilename = tempfile.mktemp (".txt")open (filename, "w").write ("This is a test")win32api.ShellExecute ( 0, "print", filename, # # If this is None, the default printer will # be used anyway. # '/d:"%s"' % win32print.GetDefaultPrinter (), ".", 0)
import win32printimport win32uiimport win32condef print2Printer(): INCH = 1440 hDC = win32ui.CreateDC () hDC.CreatePrinterDC (win32print.GetDefaultPrinter ()) hDC.StartDoc ("Test doc") hDC.StartPage () hDC.SetMapMode (win32con.MM_TWIPS) hDC.DrawText ("TEST HELLO WORLD! CORSS FIREWALL, WE TOUCH THE WORLD!", (0, INCH * -1, INCH * 8, INCH * -2), win32con.DT_CENTER) hDC.EndPage () hDC.EndDoc ()print2Printer()
若在hDC.DrawText()中传的是空字符串,则可以实现空走纸。
但实际上这只是打印自己制定的字符串, 并且打印出来会显示txt的文件名。所以我更倾向于使用windows的cmd指令打印指定文件。
3、Python利用win32连接打印机自动打印
import win32printimport win32uifrom PIL import Image, ImageWin#物理宽度、高度PHYSICALWIDTH = 110PHYSICALHEIGHT = 111#物理偏移位置PHYSICALOFFSETX = 112PHYSICALOFFSETY = 113printer_name = win32print.GetDefaultPrinter ()#选择图片路径file_name = “biaoqian.png”hDC = win32ui.CreateDC ()hDC.CreatePrinterDC (printer_name)printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)#printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)#打开图片bmp = Image.open (file_name)print(bmp.size)ratios = [1.0 * 1754 / bmp.size[0], 1.0 * 1240 / bmp.size[1]]scale = min (ratios)print(ratios)print(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_height)x1 = int ((printer_size[0] - scaled_width) / 2)y1 = int ((printer_size[1] - scaled_height) / 2)#横向位置坐标x1 = 1580#竖向位置坐标y1 = 30#4倍为自适应图片实际尺寸打印x2 = x1 + bmp.size[0]*4y2 = y1 + bmp.size[1]*4dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))hDC.EndPage ()hDC.EndDoc ()hDC.DeleteDC ()
新闻热点
疑难解答