import win32print
import win32ui
from PIL import Image, ImageWin

class PrintLib():
    #
    # Constants for GetDeviceCaps
    #
    #
    # HORZRES / VERTRES = printable area
    #
    HORZRES = 8
    VERTRES = 10
    #
    # LOGPIXELS = dots per inch
    #
    LOGPIXELSX = 88
    LOGPIXELSY = 90
    #
    # PHYSICALWIDTH/HEIGHT = total area
    #
    PHYSICALWIDTH = 110
    PHYSICALHEIGHT = 111
    #
    # PHYSICALOFFSETX/Y = left / top margin
    #
    PHYSICALOFFSETX = 112
    PHYSICALOFFSETY = 113

    autorotate = False

    def printfile(self,filename,printername):
        #
        # You can only write a Device-independent bitmap
        #  directly to a Windows device context; therefore
        #  we need (for ease) to use the Python Imaging
        #  Library to manipulate the image.
        #
        # Create a device context from a named printer
        #  and assess the printable size of the paper.
        #
        hDC = win32ui.CreateDC ()
        hDC.CreatePrinterDC (printername)
        printable_area = hDC.GetDeviceCaps (PrintLib.HORZRES), hDC.GetDeviceCaps (PrintLib.VERTRES)
        printer_size = hDC.GetDeviceCaps (PrintLib.PHYSICALWIDTH), hDC.GetDeviceCaps (PrintLib.PHYSICALHEIGHT)
        printer_margins = hDC.GetDeviceCaps (PrintLib.PHYSICALOFFSETX), hDC.GetDeviceCaps (PrintLib.PHYSICALOFFSETY)
        print "Printer",printername
        print "Printable area",printable_area
        print "Printer size",printer_size
        print "Printer margins",printer_margins

        #
        # Open the image, rotate it if it's wider than
        #  it is high, and work out how much to multiply
        #  each pixel by to get it as big as possible on
        #  the page without distorting.
        #
        bmp = Image.open (filename)
        bmp=bmp.convert('RGB')
        if self.autorotate and bmp.size[0] > bmp.size[1]:
          bmp = bmp.rotate (90)

        ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
        scale = min (ratios)

        #
        # Start the print job, and draw the bitmap to
        #  the printer device at the scaled size.
        #
        hDC.StartDoc (filename)
        hDC.StartPage ()

        dib = ImageWin.Dib (bmp)
        scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
##        x1 = int ((printer_size[0] - scaled_width) / 2)
##        y1 = int ((printer_size[1] - scaled_height) / 2)
        x1 = 0
        y1 = 0
        x2 = x1 + scaled_width
        y2 = y1 + scaled_height
        dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))

        hDC.EndPage ()
        hDC.EndDoc ()
        hDC.DeleteDC ()
