Example #1
0
def is_image(fs):
    try:
        wim = wImage(blob=fs)
        if wim.format not in AVAILABLE_FORMAT:
            raise
    except:
        return False
    else:
        return True
Example #2
0
def get_prop(fs):
    exif = {}
    im = wImage(blob=fs)
    exif.update(
        (k[5:], v) for k, v in im.metadata.items() if k.startswith('exif:'))
    p = {
        'width': im.width,
        'height': im.height,
        'filesize': len(fs),
        'exif': exif,
    }
    return p
Example #3
0
def print_bill():
    print("asdad")
    receipt_from_tailpos = loads(request.get_data(as_text=True))
    for_printing = receipt_from_tailpos['data']

    print(for_printing)

    #print(loads(for_receipt['data']['mop'])[0]['translation_text'])
    #reshaped_text = arabic_reshaper.reshape(loads(for_receipt['data']['mop'])[0]['translation_text'])
    #rev_text = reshaped_text[::-1]  # slice backwards

    # Some variable
    port_serial = "/dev/rfcomm4"

    bluetoothSerial = serial.Serial(port_serial, baudrate=115200, timeout=1)
    print(bluetoothSerial)
    fontPath = "/usr/share/fonts/opentype/fonts-hosny-thabit/Thabit.ttf"

    tmpImage = 'test1.png'
    printWidth = 250

    # Get the characters in order
    textReshaped = arabic_reshaper.reshape(for_printing['company'])
    textDisplay = get_display(textReshaped)

    # PIL can't do this correctly, need to use 'wand'.
    # Based on
    # https://stackoverflow.com/questions/5732408/printing-bidi-text-to-an-image

    im = wImage(width=printWidth, height=36, background=wColor('#ffffff'))

    draw = wDrawing()
    draw.text_alignment = 'center';
    draw.text_antialias = False
    draw.text_encoding = 'utf-8'
    draw.text_kerning = 0.0
    draw.font = fontPath
    draw.font_size = 36
    draw.text(printWidth, 22, textDisplay)
    draw(im)
    im.save(filename=tmpImage)

    # Print an image with your printer library
    printertest = printer.File(port_serial)
    printertest.set(align="right")
    printertest.image(tmpImage)
    printertest.cut()
    print("SAMOKA GYUD Oi")
    bluetoothSerial.close()
    return {}
Example #4
0
def getJP2asPIL(book_id, ia_page_index, scale=0.5):

    tar_filename = 'scandata/%s/%s_jp2.tar' % (book_id, book_id)
    tar_file = tarfile.open(tar_filename)

    jp2_file = '%s_jp2/%s_%04d.jp2' % (book_id, book_id, int(ia_page_index) + 1)
    jp2_data = tar_file.extractfile(jp2_file)

    # Use Wand to read jp2, then pass to PIL as png
    w_image = wImage(blob=jp2_data)
    w_image.resize(int(w_image.width * scale), int(w_image.height * scale))

    image = pImage.open(StringIO(w_image.make_blob('png')))
    del w_image

    return image
Example #5
0
def getJP2asPIL(book_id, ia_page_index, scale=0.5):

    tar_filename = 'scandata/%s/%s_jp2.tar' % (book_id, book_id)
    tar_file = tarfile.open(tar_filename)

    jp2_file = '%s_jp2/%s_%04d.jp2' % (book_id, book_id,
                                       int(ia_page_index) + 1)
    jp2_data = tar_file.extractfile(jp2_file)

    # Use Wand to read jp2, then pass to PIL as png
    w_image = wImage(blob=jp2_data)
    w_image.resize(int(w_image.width * scale), int(w_image.height * scale))

    image = pImage.open(StringIO(w_image.make_blob('png')))
    del w_image

    return image
Example #6
0
def processPage(book_id, page_id):

    t0 = clock()

    tar_filename = 'scandata/%s/%s_jp2.tar' % (book_id, book_id)
    tar_file = tarfile.open(tar_filename)

    jp2_file = '%s_jp2/%s_%04d.jp2' % (book_id, book_id, ia_page_index)
    jp2_info = tar_file.getmember(jp2_file)
    jp2_data = tar_file.extractfile(jp2_file)

    scale = 0.5

    # Use Wand to read jp2, then pass to PIL as png
    w_image = wImage(blob=jp2_data)
    #w_image.resize(int(w_image.width*scale), int(w_image.height*scale)) # Improve performance?
    image = pImage.open(StringIO(w_image.make_blob('png')))

    t1 = clock()
    print 'Loaded image in', t1 - t0, 's'

    # Compression analysis
    raw_size = image.size[0] * image.size[1] * mode_to_bpp[image.mode] / 8
    compression = float(jp2_info.size) / raw_size

    # Contrast analysis
    contrast_info = processContrast(image, book_id, page_id)

    print 'Processed in', clock() - t1, 's'

    info = {
        'width': w_image.width,
        'height': w_image.height,
        'depth': w_image.depth,
        'file_size': jp2_info.size,
        'raw_size': raw_size,
        'compression_ratio': compression
    }

    print info
    print contrast_info

    del image
    del w_image
Example #7
0
def processPage(book_id, page_id):

    t0 = clock()

    tar_filename = 'scandata/%s/%s_jp2.tar' % (book_id, book_id)
    tar_file = tarfile.open(tar_filename)

    jp2_file = '%s_jp2/%s_%04d.jp2' % (book_id, book_id, ia_page_index)
    jp2_info = tar_file.getmember(jp2_file)
    jp2_data = tar_file.extractfile(jp2_file)

    scale = 0.5

    # Use Wand to read jp2, then pass to PIL as png
    w_image = wImage(blob=jp2_data)
    #w_image.resize(int(w_image.width*scale), int(w_image.height*scale)) # Improve performance?
    image = pImage.open(StringIO(w_image.make_blob('png')))

    t1 = clock()
    print 'Loaded image in', t1 - t0, 's'

    # Compression analysis
    raw_size = image.size[0] * image.size[1] * mode_to_bpp[image.mode] / 8
    compression = float(jp2_info.size) / raw_size

    # Contrast analysis
    contrast_info = processContrast(image, book_id, page_id)

    print 'Processed in', clock() - t1, 's'

    info = {
        'width': w_image.width,
        'height': w_image.height,
        'depth': w_image.depth,
        'file_size': jp2_info.size,
        'raw_size': raw_size,
        'compression_ratio': compression
    }

    print info
    print contrast_info

    del image
    del w_image
Example #8
0
            #create a blank new page
            if new_page:
                document.add_page_break()

            #remove the images in the images buffer
            imgs_per_page = []

        #for every image in the pdf file send it to the images butter (imgs_per_page)
        page0 = input1.getPage(page_number)
        dst_pdf = PyPDF4.PdfFileWriter()
        dst_pdf.addPage(page0)
        pdf_bytes = io.BytesIO()
        dst_pdf.write(pdf_bytes)
        pdf_bytes.seek(0)
        page_img = wImage(file=pdf_bytes, resolution=resolution)
        page_img = page_img.make_blob('JPG')
        imgs_per_page.append(page_img)

        sys.stdout.flush()
        sys.stdout.write(
            "\r{0}.".format("Converting page " + str(page_number + 1) +
                            " of " + str(n_pages)))

    #if there are still images in the butter put them in a new page by repeating the above scrpt
    # NOTE: just a repetition of the code above
    if len(imgs_per_page) != 0:
        insert_images(document, sizes, imgs_per_page, right_page)

        #since this is supposed to be the last page i don't need to flip it
        #right_page = not right_page
def image_specs_extractor(file, technical_notes=None, media_info_path='mediainfo'):
	height = None
	width = None
	imageFormat = None  # todo: make more accurate
	colorspace = None  # todo: change to colorspace
	file_format = None
	compressionMode = None
	bitDepth = None
	imageFormat = None
	compression = None
	compressionMode = None
	bitDepth = None
	chroma_subsampling = None




	# standard Python
	file_format = mimetypes.types_map[os.path.splitext(file)[1].lower()]

	# using pillow
	try:
		with Image.open(file) as im:
			height = im.size[1]
			width = im.size[0]

			colorspace = im.mode

			# using MediaInfo
			try:
				mediaInfoData = subprocess.check_output([media_info_path, '--Output=XML', file], universal_newlines=True)
			except FileNotFoundError as d:
				raise MediaInfoException("Error running mediainfo" + str(d))
			dom = parseString(mediaInfoData)
			for node in dom.getElementsByTagName("Color_space"):
				colorspace = node.firstChild.data

			for node in dom.getElementsByTagName("Chroma_subsampling"):
				chroma_subsampling = node.firstChild.data

			for node in dom.getElementsByTagName("Format"):
				imageFormat = node.firstChild.data

			for node in dom.getElementsByTagName("Compression_mode"):
				compression = node.firstChild.data
			if compression == "Lossy":
				compressionMode = CompressionModes.LOSSY
			elif compression == "Lossless":
				compressionMode = CompressionModes.LOSSLESS
			else:
				compressionMode = CompressionModes.UNKNOWN

			try:
				bitDepth = im.bits
			except:
				for node in dom.getElementsByTagName("Bit_depth"):
					bd = node.firstChild.data
					bitDepth = cleanup_bitdepth(bd)
	except OSError as e:
		print("Unable to use Pillow, Using ImageMagick instead")
		with wImage(filename=file) as im:
			imageFormat = im.format
			height = im.width
			width = im.height
			bitDepth = im.depth
			colorspace = im.colorspace
			if compressionMode is None:
				compressionMode = "NA"

			pass
		#TODO: get alternative metadata extractor

	# print(dom.toprettyxml())



	xml = Technical(fileFormat=file_format,
					height=height,
					width=width,
					colorBitDepth=bitDepth)
	if imageFormat:
		xml.imageFormat = imageFormat
	xml.colorSpace = colorspace
	if chroma_subsampling:
		xml.chromaSubsampling = chroma_subsampling

	if compressionMode:
		xml.compressionMode = compressionMode
	if technical_notes:
		assert (isinstance(technical_notes, str))
		xml.additionalTechnicalNotes = technical_notes
	return xml
Example #10
0
def print_receipt():

    receipt_from_tailpos = loads(request.get_data(as_text=True))
    for_printing = receipt_from_tailpos['data']
    print(for_printing)

    port_serial = "/dev/rfcomm0"

    bluetoothSerial = serial.Serial(port_serial, baudrate=115200, timeout=1)
    #fontPath = "/home/jiloysss/Documents/spiceco/aljazeera-font/FontAljazeeraColor-lzzD.ttf"
    fontPath = "/home/pi/FontAljazeeraColor-lzzD.ttf"
    tmpImage = 'receipt.png'
    #printWidth = 375
    printWidth = 570

    height = 600
    draw = wDrawing()
    draw.font = fontPath

    #COMPANY ==============
    draw.font_size = 34

    draw.text(x=180,y=75,body=for_printing['company'])


    #DATE ==================
    split_date = for_printing['date'].split()
    draw.font_size = 26
    draw.text(x=5,y=110,body=split_date[0])
    draw.text(x=260,y=110,body=split_date[1])

    #ORDER TYPE ==============
    draw.font_size = 26
    draw.text(x=5,y=145,body="Order Type: " +  for_printing['ordertype'])
    y_value = 145
    #HEADER ==========

    if for_printing['header']:
        header_value = 160
        for x in for_printing['header'].split("\n"):
            y_value = y_value + 35
            header_value = header_value + 25
            draw.text_alignment = "center"
            draw.text(x=180,y=header_value,body=x)

    draw.text_alignment = "undefined"

    draw.text(x=5,y=y_value + 35 ,body="=====================================")

    #ITEM PURCHASES
    y_value = y_value + 30
    for idx,i in enumerate(for_printing['lines']):
        if idx != 0:
            height += 35
        draw.gravity = "north_east"
        draw.text(x=5,y=y_value + 10,body=format(float(i['qty'] * i['price']), '.2f'))
        draw.gravity = "forget"

        if len(i['item_name']) > 22:
            quotient = len(i['item_name']) / 22
            for xxx in range(0,int(quotient)):
                if idx != 0:
                    height += 35
                y_value = y_value + 35
                draw.text(x=5,y=y_value,body=i['item_name'][xxx * 22: (xxx+1) * 22])
            translation_text = ""
            if i['translation_text']:
                textReshaped = arabic_reshaper.reshape(i['translation_text'])
                textDisplay = get_display(textReshaped)
                translation_text = "(" + textReshaped + ")"
            y_value = y_value + 35
            draw.text(x=5,y=y_value,body=i['item_name'][(int(quotient)*22): len(i['item_name'])] + translation_text )

        else:
            translation_text = ""
            if i['translation_text']:
                textReshaped = arabic_reshaper.reshape(i['translation_text'])
                textDisplay = get_display(textReshaped)
                translation_text = "(" + textReshaped + ")"
            y_value = y_value + 35
            draw.text(x=5,y=y_value,body=i['item_name'] )
            y_value = y_value + 35
            draw.text(x=5,y=y_value,body= translation_text)


    draw.text(x=5,y=y_value+35,body="=====================================")

    y_value = y_value + 35

    #SUBTOTAL
    draw.text(x=5,y=y_value + 35,body="Subtotal")
    draw.gravity = "north_east"
    draw.text(x=5,y=y_value + 5,body=for_printing['subtotal'])
    draw.gravity = "forget"

    y_value = y_value + 35

    #DISCOUNT

    draw.text(x=5,y=y_value + 35,body="Discount")
    draw.gravity = "north_east"
    draw.text(x=5,y=y_value + 5,body=for_printing['discount'])
    draw.gravity = "forget"

    #TAXES VALUES
    if len(for_printing['taxesvalues']) > 0:
        y_value = y_value + 35
        for idx,iii in enumerate(for_printing['taxesvalues']):
            if idx != 0:
                height += 35
            y_value = y_value + 35

            draw.text(x=5,y=y_value,body=iii['name'])
            draw.gravity = "north_east"
            draw.text(x=5,y=y_value - 25,body=str(format(round(float(iii['totalAmount']),2), '.2f')))
            draw.gravity = "forget"

    #MODE OF PAYMENT
    for idx, ii in enumerate(loads(for_printing['mop'])):
        if idx != 0:
            height += 35
        y_value = y_value + 70
        type = ii['type']

        if ii['translation_text']:
            textReshaped = arabic_reshaper.reshape(ii['translation_text'])
            textDisplay = get_display(textReshaped)
            type += "(" + textReshaped + ")"

        draw.text(x=5,y=y_value,body=type)
        draw.gravity = "north_east"
        draw.text(x=5,y=y_value - 25,body=str(format(float(ii['amount']), '.2f')))
        draw.gravity = "forget"



    #TOTAL AMOUNT

    draw.text(x=5,y=y_value + 35,body="Total Amount")
    draw.gravity = "north_east"
    draw.text(x=5,y=y_value + 5,body=str(format(float(for_printing['total_amount']), '.2f')))
    draw.gravity = "forget"

    #CHANGE

    draw.text(x=5,y=y_value + 70,body="Change")
    draw.gravity = "north_east"
    draw.text(x=5,y=y_value + 43,body=str(format(float(for_printing['change']), '.2f')))
    draw.gravity = "forget"

    draw.text(x=5,y=y_value+105,body="=====================================")

    #FOOTER ==========

    if for_printing['footer']:
        header_value = y_value+105
        for x in for_printing['footer'].split("\n"):
            y_value = y_value + 35
            header_value = header_value + 25
            draw.text_alignment = "center"
            draw.text(x=180,y=header_value,body=x)

    im = wImage(width=printWidth, height=height, background=wColor('#ffffff'))
    draw(im)

    im.save(filename=tmpImage)

    # Print an image with your printer library
    printertest = printer.File(port_serial)
    printertest.set(align="left")
    printertest.image(tmpImage)
    printertest.cut()
    print("SAMOKA GYUD Oi")
    bluetoothSerial.close()
    return {}
Example #11
0
def write_order(order, usb_printer=None, print_item_code=True):
    port_serial = "/dev/rfcomm1"
    home = str(Path.home())
    bluetoothSerial = serial.Serial(port_serial, baudrate=115200, timeout=1)
    company_name = "house_of_spices"
    fontPath = home + "/tailorder-server/fonts/" + company_name + ".ttf"

    tmpImage = 'print_images/kitchen.png'
    printWidth = 570

    height = 500
    draw = wDrawing()
    draw.font = fontPath

    draw.font_size = 30

    y_value = 30
    draw.text(x=5, y=y_value, body="Order Id: ")
    draw.text(x=160, y=y_value, body=str(order.id))

    y_value = y_value + 35
    draw.text(x=5, y=y_value, body="Table Number: ")
    draw.text(x=230, y=y_value, body=str(order.table_no))

    y_value = y_value + 35
    draw.text(x=5, y=y_value, body="Type: ")
    draw.text(x=100, y=y_value, body=str(order.type))

    lines = []
    for i in order.items:
        lines.append(i.__dict__)

    # Headers
    header_line = line_block([
        {
            'text': 'Qty',
            'align': '<',
            'width': QTY_WIDTH
        },
        {
            'text': 'Item',
            'align': '<',
            'width': ITEM_WIDTH
        },
    ])
    y_value = y_value + 45
    draw.text(x=5, y=y_value, body=str(header_line))

    # Lines
    for line in lines:
        line_text = line_block([
            {
                'text': line['qty'],
                'align': '<',
                'width': QTY_WIDTH
            },
            {
                'text': line['item_name'],
                'align': '<',
                'width': ITEM_WIDTH
            },
        ])
        y_value = y_value + 35
        draw.text(x=5, y=y_value, body=str(line_text))

        if print_item_code:
            item_code = line_block([{
                'text': '-',
                'align': '<',
                'width': QTY_WIDTH
            }, {
                'text': line['item_code'],
                'align': '<',
                'width': ITEM_WIDTH
            }])
            y_value = y_value + 35
            draw.text(x=5, y=y_value, body=str(item_code))
    if order.remarks:
        y_value = y_value + 70
        draw.text(x=5, y=y_value, body="Remarks: ")
        draw.text(x=180, y=y_value, body=str(order.remarks))

    y_value = y_value + 70
    draw.text(x=5, y=y_value, body="Printed on: ")
    draw.text(x=180, y=y_value, body=str(time.ctime()))

    im = wImage(width=printWidth, height=height, background=wColor('#ffffff'))
    draw(im)
    im.save(filename=tmpImage)

    #basewidth = 230
    #baseheight = 221
    #logo = "logos/logo.png"
    #img = Image.open(logo)
    #wpercent = (basewidth / float(img.size[0]))
    #img = img.resize((basewidth, baseheight), PIL.Image.ANTIALIAS)
    #img.save(logo)

    # Print an image with your printer library
    printertest = printer.File(port_serial)
    printertest.set(align="center")
    #printertest.image(logo)
    printertest.image(tmpImage)
    printertest.cut()

    bluetoothSerial.close()
Example #12
0
import pyocr.builders
import io
import os
import cv2
from matplotlib import pyplot as plt

tess = pyocr.tesseract
lang = 'deu'
if not lang in tess.get_available_languages():
    raise BaseException('Tesseract ' + lang + ' Sprachpaket nicht gefunden!')

req_image = []
filename = "./data/set1.pdf"
filename_png = "./data/page1.png"

image_pdf = wImage(filename=filename, resolution=300)
image_png = image_pdf.convert('png')

for img in image_png.sequence:
    img_page = wImage(image=img)
    req_image.append(img_page.make_blob('png'))
    img_page.colorspace = 'rgb'
    img_page.strip()
    img_page.save(filename=filename_png)

    break  # only first page of PDF

for img in req_image:
    txt = tess.image_to_string(pImage.open(io.BytesIO(img)),
                               lang=lang,
                               builder=pyocr.builders.TextBuilder())
from PIL import Image
from wand.image import Image as wImage
from wand.display import display
from StringIO import StringIO
from PIL.PngImagePlugin import PngImageFile
import iconfile

pin = iconfile.pinIcon.GetData()
wim = wImage(blob=pin)
display(wim)
im = Image.open("c:\p.png")
#help(im)
if isinstance(im, PngImageFile):
    print "pil instance"
fil = StringIO()
im.save(fil, 'PNG')
wim = wImage(blob=fil.getvalue())
help(wim)
if isinstance(wim, wImage):
    print "wim"
fil.close()
#display(wim)
fil2 = StringIO()
wim.save(fil2)
im2 = Image.open(StringIO(fil2.getvalue()))
im2.save("c:\\test2.png")
Example #14
0
def create_thumbnail(fs):
    im = wImage(blob=fs)
    im.transform(resize='x150>')
    return im
Example #15
0
def print_report():

    receipt_from_tailpos = loads(request.get_data(as_text=True))
    for_printing = receipt_from_tailpos['data']
    type_of_printing = receipt_from_tailpos['type']
    print(for_printing)

    port_serial = "/dev/rfcomm0"
    home = str(Path.home())
    bluetoothSerial = serial.Serial(port_serial, baudrate=115200, timeout=1)
    company_name = for_printing['company'].lower().replace(" ", "_")
    print(company_name)
    fontPath = home + "/tailorder-server/fonts/" + company_name + ".ttf"
    print(fontPath)
    tmpImage = 'print_images/report.png'
    printWidth = 570

    height = 600
    draw = wDrawing()
    draw.font = fontPath

    #COMPANY ==============
    draw.font_size = 34
    y_value = 30
    draw.text(x=180, y=y_value, body=for_printing['company'])
    draw.font_size = 26

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="=====================================")

    y_value = y_value + 35

    draw.text_alignment = "center"

    draw.text(x=300, y=y_value, body=for_printing['reportType'])

    draw.text_alignment = "undefined"

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="=====================================")

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="Opened: " + for_printing['opened'])

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="Opened: " + for_printing['closed'])

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="=====================================")

    y_value = y_value + 35
    labels = [
        "Opening Amount",
        "Expected Drawer",
        "Actual Money",
    ]
    for i in labels:
        draw.text(x=5, y=y_value, body=i)
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value - 35,
                  body=for_printing[i.lower().replace(" ", "_")])
        draw.gravity = "forget"
        y_value = y_value + 35

    draw.text(x=5, y=y_value, body=for_printing['short_or_overage'])
    draw.gravity = "north_east"
    draw.text(x=5,
              y=y_value - 35,
              body=for_printing["short_or_overage_amount"])
    draw.gravity = "forget"

    y_value = y_value + 35

    draw.text(x=5, y=y_value, body="=====================================")

    y_value = y_value + 35

    labels = [
        "Cash Sales",
        "Total Net Sales",
        "Total Net Sales with Vat",
        "Payouts",
        "Payins",
    ]
    for i in labels:
        draw.text(x=5, y=y_value, body=i)
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value - 35,
                  body=for_printing[i.lower().replace(" ", "_")])
        draw.gravity = "forget"
        y_value = y_value + 35

    if len(for_printing['total_taxes']) > 0:
        for i in for_printing['total_taxes']:
            height += 35
            draw.text(x=5, y=y_value, body=i['name'])
            draw.gravity = "north_east"
            draw.text(x=5, y=y_value - 35, body=str(i['totalAmount']))
            draw.gravity = "forget"
            y_value = y_value + 35

    labels = ["Discount", "Cancelled", "Voided", "Transactions", "Loyalty"]
    for i in labels:
        height += 35
        draw.text(x=5, y=y_value, body=i)
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value - 35,
                  body=str(for_printing[i.lower().replace(" ", "_")]))
        draw.gravity = "forget"
        y_value = y_value + 35
    height += 35
    draw.text(x=5, y=y_value, body="=====================================")

    y_value = y_value + 35
    labels = [
        "Dine in",
        "Takeaway",
        "Delivery",
        "Online",
        "Family",
    ]
    for i in labels:
        if float(for_printing[i.lower().replace(" ", "_")]) > 0:
            height += 35
            draw.text(x=5, y=y_value, body=i)
            draw.gravity = "north_east"
            draw.text(x=5,
                      y=y_value - 35,
                      body=for_printing[i.lower().replace(" ", "_")])
            draw.gravity = "forget"
            y_value = y_value + 35

    if len(for_printing['categories_total_amounts']) > 0:
        for i in for_printing['categories_total_amounts']:
            height += 35
            draw.text(x=5, y=y_value, body=i['name'])
            draw.gravity = "north_east"
            draw.text(x=5,
                      y=y_value - 35,
                      body=str(format(float(i['total_amount']), '.2f')))
            draw.gravity = "forget"
            y_value = y_value + 35
    else:
        y_value = y_value + 35
    height += 35
    draw.text(x=5, y=y_value, body="=====================================")
    y_value = y_value + 35

    if len(for_printing['mop_total_amounts']) > 0:
        for i in for_printing['mop_total_amounts']:
            height += 35
            draw.text(x=5, y=y_value, body=i['name'])
            draw.gravity = "north_east"
            draw.text(x=5,
                      y=y_value - 35,
                      body=str(format(float(i['total_amount']), '.2f')))
            draw.gravity = "forget"
            y_value = y_value + 35
    if len(for_printing['mop_total_amounts']) > 0:
        height += 35

        draw.text(x=5, y=y_value, body="=====================================")

    im = wImage(width=printWidth, height=height, background=wColor('#ffffff'))
    draw(im)
    im.save(filename=tmpImage)

    basewidth = 230
    baseheight = 221
    logo = "logos/logo.png"
    img = Image.open(logo)
    wpercent = (basewidth / float(img.size[0]))
    img = img.resize((basewidth, baseheight), PIL.Image.ANTIALIAS)
    img.save(logo)

    # Print an image with your printer library
    printertest = printer.File(port_serial)
    printertest.set(align="center")
    printertest.image(logo)
    printertest.image(tmpImage)
    printertest.cut()

    bluetoothSerial.close()

    return {}
Example #16
0
def print_receipt():
    receipt_from_tailpos = loads(request.get_data(as_text=True))
    for_printing = receipt_from_tailpos['data']
    type_of_printing = receipt_from_tailpos['type']

    port_serial = "/dev/rfcomm0"
    home = str(Path.home())
    bluetoothSerial = serial.Serial(port_serial, baudrate=115200, timeout=1)
    company_name = for_printing['company'].lower().replace(" ", "_")
    fontPath = home + "/tailorder-server/fonts/" + company_name + ".ttf"
    tmpImage = 'print_images/receipt.png'
    #printWidth = 375
    printWidth = 570

    height = 500
    draw = wDrawing()
    draw.font = fontPath

    #COMPANY ==============
    company_translation = ""
    if for_printing['companyTranslation']:
        textReshaped = arabic_reshaper.reshape(
            for_printing['companyTranslation'])
        company_translation = get_display(textReshaped)
    draw.font_size = 34
    y_value = 30
    draw.text(x=180, y=y_value, body=for_printing['company'])
    draw.text(x=180, y=y_value + 35, body=company_translation)

    y_value = y_value + 45
    draw.font_size = 26

    #HEADER ==========
    if for_printing['header']:
        draw.text_alignment = "center"
        header_value = y_value
        header_array = for_printing['header'].split("\n")
        header_array_translation = for_printing['headerTranslation'].split(
            "\n")

        for x in range(0, len(header_array)):
            if header_array[x]:
                translation = ""
                if x < len(header_array_translation
                           ) and header_array_translation[x]:
                    textReshaped = arabic_reshaper.reshape(
                        header_array_translation[x])
                    translation = get_display(textReshaped)

                y_value = y_value + 40
                header_value = header_value + 25

                draw.text(x=300,
                          y=header_value,
                          body=header_array[x] + translation)

    draw.text_alignment = "undefined"
    if for_printing['vat_number']:
        y_value = y_value + 35
        header_value = header_value + 25
        draw.text(x=5,
                  y=y_value,
                  body="VAT No.: " + for_printing['vat_number'])

    if for_printing['ticket_number']:
        header_value = header_value + 25
        draw.text(x=330,
                  y=y_value,
                  body="Ticket Number: " + for_printing['ticket_number'])

    y_value = y_value + 35

    #DATE ==================
    split_date = for_printing['date'].split()
    draw.font_size = 26
    draw.text(x=5, y=y_value, body=split_date[0])
    draw.gravity = "north_east"
    draw.text(x=5, y=y_value - 20, body=split_date[1])
    draw.gravity = "forget"

    y_value = y_value + 35

    #ORDER TYPE ==============
    draw.font_size = 26
    draw.text(x=5, y=y_value, body="Order Type: " + for_printing['ordertype'])

    draw.text(x=5,
              y=y_value + 35,
              body="=====================================")

    #ITEM PURCHASES
    y_value = y_value + 30
    for idx, i in enumerate(for_printing['lines']):
        if idx != 0:
            height += 35
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value + 10,
                  body=format(float(i['qty'] * i['price']), '.2f'))
        draw.gravity = "forget"

        draw.text(x=340, y=y_value + 35, body=str(i['qty']))

        if len(i['item_name']) > 25:
            quotient = len(i['item_name']) / 25
            for xxx in range(0, int(quotient)):
                if idx != 0:
                    height += 35
                y_value = y_value + 35
                draw.text(x=5,
                          y=y_value,
                          body=i['item_name'][xxx * 25:(xxx + 1) * 25])

            y_value = y_value + 35
            draw.text(x=5,
                      y=y_value,
                      body=i['item_name'][(int(quotient) *
                                           25):len(i['item_name'])])
            if i['translation_text']:
                y_value = y_value + 35
                textReshaped = arabic_reshaper.reshape(i['translation_text'])
                textDisplay = get_display(textReshaped)
                translation_text = textDisplay

                draw.text(x=5, y=y_value, body=translation_text)

        else:
            y_value = y_value + 35
            if idx != 0:
                height += 35
            draw.text(x=5, y=y_value, body=i['item_name'])
            if i['translation_text']:
                height += 35
                y_value = y_value + 35
                textReshaped = arabic_reshaper.reshape(i['translation_text'])
                textDisplay = get_display(textReshaped)
                translation_text = textDisplay
                draw.text(x=5, y=y_value, body=translation_text)

    draw.text(x=5,
              y=y_value + 35,
              body="=====================================")

    y_value = y_value + 35

    #SUBTOTAL
    textReshaped = arabic_reshaper.reshape("المبلغ الاجمالي")
    textDisplaySubtotal = get_display(textReshaped)
    draw.text(x=5, y=y_value + 35, body="Subtotal" + textDisplaySubtotal)
    draw.gravity = "north_east"
    draw.text(x=5, y=y_value + 5, body=for_printing['subtotal'])
    draw.gravity = "forget"

    y_value = y_value + 35

    #DISCOUNT
    textReshaped = arabic_reshaper.reshape("الخصم")
    textDisplayDiscount = get_display(textReshaped)
    draw.text(x=5, y=y_value + 35, body="Discount" + textDisplayDiscount)
    draw.gravity = "north_east"
    draw.text(x=5, y=y_value + 5, body=for_printing['discount'])
    draw.gravity = "forget"

    if for_printing['loyalty'] > 0:
        y_value = y_value + 35
        #LOYALTY
        textReshaped = arabic_reshaper.reshape("وفاء")
        textDisplayDiscount = get_display(textReshaped)
        draw.text(x=5, y=y_value + 35, body="Loyalty" + textDisplayDiscount)
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value + 5,
                  body=str(
                      format(round(float(for_printing['loyalty']), 2), '.2f')))
        draw.gravity = "forget"
        height += 35

    #TAXES VALUES
    if len(for_printing['taxesvalues']) > 0:
        y_value = y_value + 35
        for idx, iii in enumerate(for_printing['taxesvalues']):
            if idx != 0:
                height += 35
            y_value = y_value + 35
            tax_translation = ""
            if iii['translation']:
                height += 35
                textReshaped = arabic_reshaper.reshape(iii['translation'])
                tax_translation = get_display(textReshaped)

            draw.text(x=5, y=y_value, body=iii['name'] + tax_translation)
            draw.gravity = "north_east"
            draw.text(x=5,
                      y=y_value - 25,
                      body=str(
                          format(round(float(iii['totalAmount']), 2), '.2f')))
            draw.gravity = "forget"

    if len(for_printing['taxesvalues']) == 0:
        y_value = y_value + 35

    #MODE OF PAYMENT
    if type_of_printing != "Bill":
        for idx, ii in enumerate(loads(for_printing['mop'])):
            if idx != 0:
                height += 35
            y_value = y_value + 35
            type = ii['type']

            if ii['translation_text']:
                textReshaped = arabic_reshaper.reshape(ii['translation_text'])
                textDisplay = get_display(textReshaped)
                type += textDisplay

            draw.text(x=5, y=y_value, body=type)
            draw.gravity = "north_east"
            draw.text(x=5,
                      y=y_value - 25,
                      body=str(format(float(ii['amount']), '.2f')))
            draw.gravity = "forget"

    #TOTAL AMOUNT
    height += 35
    textReshaped = arabic_reshaper.reshape("المبلغ الاجمالي")
    textDisplayTA = get_display(textReshaped)
    draw.text(x=5, y=y_value + 35, body="Total Amount" + textDisplayTA)
    draw.gravity = "north_east"
    draw.text(x=5,
              y=y_value + 5,
              body=str(format(float(for_printing['total_amount']), '.2f')))
    draw.gravity = "forget"

    #CHANGE
    if type_of_printing != "Bill":
        height += 35
        textReshaped = arabic_reshaper.reshape("الباقي")
        textDisplayChange = get_display(textReshaped)
        draw.text(x=5, y=y_value + 70, body="Change" + textDisplayChange)
        draw.gravity = "north_east"
        draw.text(x=5,
                  y=y_value + 45,
                  body=str(format(float(for_printing['change']), '.2f')))
        draw.gravity = "forget"
    height += 40
    draw.text(x=5,
              y=y_value + 105,
              body="=====================================")

    #FOOTER ==========

    if for_printing['footer']:
        draw.text_alignment = "center"
        footer_value = y_value + 105
        footer_array = for_printing['footer'].split("\n")
        footer_array_translation = for_printing['footerTranslation'].split(
            "\n")
        for xx in range(0, len(footer_array)):
            if footer_array[xx]:
                height += 40
                translation = ""
                if xx < len(footer_array_translation
                            ) and footer_array_translation[xx]:
                    textReshaped = arabic_reshaper.reshape(
                        footer_array_translation[xx])
                    translation = get_display(textReshaped)

                footer_value = footer_value + 25
                draw.text(x=300,
                          y=footer_value,
                          body=footer_array[xx] + translation)

    im = wImage(width=printWidth, height=height, background=wColor('#ffffff'))
    draw(im)
    im.save(filename=tmpImage)

    basewidth = 230
    baseheight = 221
    logo = "logos/logo.png"
    img = Image.open(logo)
    wpercent = (basewidth / float(img.size[0]))
    img = img.resize((basewidth, baseheight), PIL.Image.ANTIALIAS)
    img.save(logo)

    # Print an image with your printer library
    printertest = printer.File(port_serial)
    printertest.set(align="center")
    printertest.image(logo)
    printertest.image(tmpImage)
    printertest.cut()

    bluetoothSerial.close()

    return {}