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.TakescareofstandardfiletypesNoneedtomessaroundwithprinterlistsGivesyounocontrolOnlyworksforwell-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.QuickandeasyYoucandecidewhichprintertouseDatamustbeprinter-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.ItworksYoucandecidewhichprintertouse(ThankstothePIL)YoucanselectloadsofimageformatsIfyou'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