用python在windows系统中打印

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

PrintTimGoldenPythonStuffWin32HowDoI...?PrintIntroductionTherequirement:toprintThisisprobablythemostwide-rangingquestionI'llhavetoaddresshere,andtheonewiththegreatestdisparitybetweenthenumberandcomplexityofsolutionsandthesimplicityoftherequirement.Theansweris:italldependswhatyou'retryingtoprint,whattoolsyouhaveatyourdisposal,andhowmuchcontrolyouneed.Ifyousimplyhaveadocument(read:fileofawell-knowntype,associatedwithoneapplication)youwishtoprint,andaren'ttoofussyaboutcontrolling,thenyoucanusetheShellExecuteapproach.Thisworks(assumingyouhavethecorrespondingapplicationsinstalled)forMicrosoftOfficedocuments,PDFfiles,textfiles,andprettymuchanymajorapplication.Tryitandsee.Thenextmostgeneralcaseiswhereyouhavesomething,forexampleatextfileorrawPCL,whichyouknowyoucansenddirectlytoaprinter.Inthatcase,youcanusethewin32printfunctionsdirectly.Ifyouhaveanimagetoprint,youcancombinethepowerofthePythonImagingLibrarywiththewin32uimoduletodoarough-and-readybutusefulprinttoanyprinter.Ifyouhaveafairamountoftexttoprint,yourbestbetistousetheReportlabPDFToolkitanditsPlatypusdocumentsystemtogeneratereadablePDFsfromanyamountoftext,andthenusetheShellExecutetechniquetoprintit.Standarddocument:useShellExecuteMakeuseofthefactthatwithinWin32,filetypes(ineffect,extensions)canbeassociatedwithapplicationsviacommandverbs.Typicallythesameapplicationwillhandleallverbs(andtypicallythoseverbsareOpenandPrint)butthat'snotstrictlynecessary.ThismeansthatyoucantelltheOStotakeyourfileandcallwhatever'snecessarytoprintit.TakescareofstandardfiletypesNoneedtomessaroundwithprinterlistsGivesyounocontrolOnlyworksforwell-defineddocument-applicationpairings.OnlyprintstodefaultprinterUPDATE:KudostoChrisCurveyforpointingoutthatyoucanspecifyaprinterbyincludingitwithad:switchintheparamssection.Don'tknowifitworksforeveryfiletype.importtempfileimportwin32apiimportwin32printfilename=tempfile.mktemp(.txt)open(filename,w).write(Thisisatest)win32api.ShellExecute(0,print,filename,##IfthisisNone,thedefaultprinterwill#beusedanyway.#'/d:%s'%win32print.GetDefaultPrinter(),.,0)UPDATE2:MatBaker&Michaelmicolousbothpointoutthatthere'sanunderdocumentedprinttoverbwhichtakestheprinternameasaparameter,enclosedinquotesifitcontainsspaces.Ihaven'tgotthistoworkbuttheybothreportsuccessforatleastsomefiletypes.importtempfileimportwin32apiimportwin32printfilename=tempfile.mktemp(.txt)open(filename,w).write(Thisisatest)win32api.ShellExecute(0,printto,filename,'%s'%win32print.GetDefaultPrinter(),.,0)Rawprintabledata:usewin32printdirectlyThewin32printmoduleoffers(almost)alltheprintingprimitivesyou'llneedtotakesomedataandthrowitataprinterwhichhasalreadybeendefinedonyoursystem.Thedatamustbeinaformwhichtheprinterwillhappilyswallow,usuallysomethingliketextorrawPCL.QuickandeasyYoucandecidewhichprintertouseDatamustbeprinter-readyimportos,sysimportwin32printprinter_name=win32print.GetDefaultPrinter()##raw_datacouldequallyberawPCL/PSreadfrom#someprint-to-fileoperation#ifsys.version_info=(3,):raw_data=bytes(Thisisatest,utf-8)else:raw_data=ThisisatesthPrinter=win32print.OpenPrinter(printer_name)try:hJob=win32print.StartDocPrinter(hPrinter,1,(testofrawdata,None,RAW))try:win32print.StartPagePrinter(hPrinter)win32print.WritePrinter(hPrinter,raw_data)win32print.EndPagePrinter(hPrinter)finally:win32print.EndDocPrinter(hPrinter)finally:win32print.ClosePrinter(hPrinter)Singleimage:usePILandwin32uiWithoutanyextratools,printinganimageonaWindowsmachineisalmostinsanelydifficult,involvingatleastthreedevicecontextsallrelatedtoeachotheratdifferentlevelsandafairamountoftrial-and-error.Fortunately,thereissuchathingasadevice-independentbitmap(DIB)whichletsyoucuttheGordianknot--oratleastsomeofit.Evenmorefortunately,thePythonImagingLibrarysupportsthebeast.Thefollowingcodedoesaquickjoboftakinganimagefileandaprinterandprintingtheimageaslargeaspossibleonthepagewithoutlosingtheaspectratio,whichiswhatyouwantmostofthetime.ItworksYoucandecidewhichprintertouse(ThankstothePIL)YoucanselectloadsofimageformatsIfyou'renotuponWindowsdevicecontexts,it'snotthemostintelligbleoftechniques.importwin32printimportwin32uifromPILimportImage,ImageWin##ConstantsforGetDeviceCaps###HORZRES/VERTRES=printablearea#HORZRES=8VERTRES=10##LOGPIXELS=dotsperinch#LOGPIXELSX=88LOGPIXELSY=90##PHYSICALWIDTH/HEIGHT=totalarea#PHYSICALWIDTH=110PHYSICALHEIGHT=111##PHYSICALOFFSETX/Y=left/topmargin#PHYSICALOFFSETX=112PHYSICALOFFSETY=113printer_name=win32print.GetDefaultPrinter()file_name=test.jpg##YoucanonlywriteaDevice-independentbitmap#directlytoaWindowsdevicecontext;therefore#weneed(forease)tousethePythonImaging#Librarytomanipulatetheimage.##Createadevicecontextfromanamedprinter#andassesstheprintablesizeofthepaper.#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)##Opentheimage,rotateitifit'swiderthan#itishigh,an

1 / 5
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功