Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.7 kB
7
Indexable
import barcode
from barcode.writer import ImageWriter
import win32print
import win32ui
from PIL import Image, ImageWin

print("Using default printer: " + win32print.GetDefaultPrinter())



def print_barcode(number):
    EAN = barcode.get_barcode_class('code128')

    with open("./lastbarcode.jpg", "wb") as f:
        try:
            EAN(number, writer=ImageWriter()).write(f)
        except Exception as e:
            print(str(e))
            quit()

    #
    # Constants for GetDeviceCaps
    #
    #
    # HORZRES / VERTRES = printable area
    #
    HORZRES = 28313
    VERTRES = 28313
    #
    # LOGPIXELS = dots per inch
    #
    LOGPIXELSX = 80
    LOGPIXELSY = 80
    #
    # PHYSICALWIDTH/HEIGHT = total area
    #
    PHYSICALWIDTH = 0
    PHYSICALHEIGHT = 0
    #
    # PHYSICALOFFSETX/Y = left / top margin
    #
    PHYSICALOFFSETX = 0
    PHYSICALOFFSETY = -100

    printer_name = win32print.GetDefaultPrinter ()
    file_name = "lastbarcode.jpg"

    #
    # 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 (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)

    #
    # 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 (file_name)
    bmp = bmp.rotate (90)

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


    #
    # Start the print job, and draw the bitmap to
    #  the printer device at the scaled size.
    #
    hDC.StartDoc (file_name)
    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)
    x2 = x1 + scaled_width
    y2 = y1 + scaled_height

    x1 = 200
    y1 = 50

    dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))

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



while True:
    user_input_num = input("Product ID: ")
    if user_input_num != "":
        print_barcode(user_input_num.upper())