Version 12 of Printing under Windows

Updated 2007-03-05 14:05:15

GWL A small routine to print a given file under Windows (note it blows up if the extension is not registered or if there is no print command for the extension -- feel free to add error checking):

 proc WindowsPrintFile {fileName {printer {}}} {
     package require csv

     ##
     ## Get the print command for this type
     ##
     set ext [file extension $fileName]
     set app [registry get [format {HKEY_CLASSES_ROOT\%s} $ext] {}]
     set app [format {HKEY_CLASSES_ROOT\%s\shell\print\command} $app]
     set cmdList {}
     foreach cmdElement [::csv::split [registry get $app {}] { }] {
          lappend cmdList [string map {%1 %1$s} $cmdElement]
     }

     ##
     ## Get the current default printer
     ##
     set currentDefaultReg [registry get {HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows} {Device}]
     set currentPrinter [lindex [split $currentDefaultReg {,}] 0]
     if {[string equal $printer {}]} {
         ##
         ## No printer specified, use default
         ##
         set printer $currentPrinter
     }

     ##
     ## Change default printer if need be
     ##
     if {![string equal $printer $currentPrinter]} {
         set tmpReg [join [concat [list $printer] [lrange [split $currentDefaultReg {,}] 1 end] ] {,} ]
         registry set {HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows} {Device} $tmpReg
     }

     ##
     ## Print the file -- catch is needed because return codes are not Unix ones!!!
     ##
     set cmd [format $printCommandArray($ext) $fileName]
     catch {eval exec $cmd} msg

     ##
     ## Restore default printer if need be
     ##
     if {![string equal $printer $currentPrinter]} {
         registry set {HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows} {Device} $currentDefaultReg
     }

     ##
     ## All done, so return 
     ##
     return;

 }

Sarnold: I recently found myself searching for a lpr replacement. IMHO PDF format is the best under Windows. This line prints directly a pdf file via Acrobat Reader:

 eval exec [auto_execok start] AcroRd32.exe /p [list [file normalize ~/Mes\ documents/report.pdf]]

See also:


Category Printing - Category Windows