Exemplo n.º 1
0
def detail(request, item_id):
    # select targeted item and create its own barcode image when user clicks
    try:
        item = Libitem.objects.get(pk=item_id)
        code = str(item.barcode)  # transfer integers into strings
        # targeted item is a book
        if item.itemtype == 'Book':
            items = Book.objects.get(pk=item_id)
            # generate barcode picture
            ean = barcode.get('ean8', code, writer=ImageWriter())
            # moving the picture to static/bar-img/books
            bar_name = item.title
            bar_pic = ean.save(bar_name)
            shutil.copy(bar_pic, 'test100/static/bar-img/book/')
            os.remove(bar_pic)
            # create url for detail page to display the barcode iamge
            bar_url = 'bar-img/book/' + bar_name + '.png'
        # targeted item is a dvd
        else:
            items = DVD.objects.get(pk=item_id)
            # generate barcode picture
            ean = barcode.get('ean8', code, writer=ImageWriter())
            # moving the picture to static/bar-img/books
            bar_name = item.title
            bar_pic = ean.save(bar_name)
            shutil.copy(bar_pic, 'test100/static/bar-img/dvd/')
            os.remove(bar_pic)
            # create url for detail page to display the barcode iamge
            bar_url = 'bar-img/dvd/' + bar_name + '.png'
        return render(request, 'test100/detail.html', {
            'item': items,
            'bar_url': bar_url
        })
    except:
        raise Http404
Exemplo n.º 2
0
def bargenerate():
    if len(name.get()) != 0 and name.get() != "Enter filename here" and len(
            Subject.get()) != 0 and Subject.get() != "Enter subject here":
        if '/' not in name.get():
            global brcode, fpath, type1, timestampStr2
            brcode = barcode.get("code128",
                                 Subject.get(),
                                 writer=ImageWriter())
            brcodesvg = barcode.get("code128", Subject.get())
            dummy = os.getcwd() + "\\images"
            if not os.path.exists(dummy):
                os.makedirs(dummy)
            fpath = os.path.join(dummy, name.get())
            brcode.save(fpath)
            dateTimeObj = datetime.now()
            timestampStr2 = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")
            type1 = 2
            storedata()
            try:
                showbrcode()
            except:
                pass
        else:
            messagebox.showinfo("", "filename can't contains '/'")
    else:
        messagebox.showinfo("", "Please Enter some filename or subject")
Exemplo n.º 3
0
def generate_barcode(string, output_extension):

    if output_extension in ('PNG', 'png'):
        ean = barcode.get('Code39', string, writer=ImageWriter())
    else:
        ean = barcode.get('Code39', string, writer=None)
    ean.default_writer_options['module_height'] = 13.0
    ean.default_writer_options['module_width'] = 0.01
    filename = ean.save(string)
    return filename
Exemplo n.º 4
0
def generate_barcode(string, output_extension):

	if output_extension in ('PNG', 'png'):
		ean = barcode.get('Code39', string, writer=ImageWriter())
	else:
		ean = barcode.get('Code39', string, writer=None)
	ean.default_writer_options['module_height'] = 13.0
	ean.default_writer_options['module_width'] = 0.01
	filename = ean.save(string)
	return filename
Exemplo n.º 5
0
async def bq(event):
    xx = await edit_or_reply(event, "`Processing...`")
    input_str = event.pattern_match.group(1)
    message = "SYNTAX: `.barcode <long text to include>`"
    reply_msg_id = event.message.id
    if input_str:
        message = input_str
    elif event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        reply_msg_id = previous_message.id
        if previous_message.media:
            downloaded_file_name = await event.client.download_media(previous_message)
            m_list = None
            with open(downloaded_file_name, "rb") as fd:
                m_list = fd.readlines()
            message = "".join(m.decode("UTF-8") + "\r\n" for m in m_list)
            os.remove(downloaded_file_name)
        else:
            message = previous_message.message
    else:
        return edit_delete(xx, "SYNTAX: `.barcode <long text to include>`")

    bar_code_type = "code128"
    try:
        bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter())
        filename = bar_code_mode_f.save(bar_code_type)
        await event.client.send_file(event.chat_id, filename, reply_to=reply_msg_id)
        os.remove(filename)
    except Exception as e:
        return await edit_delete(xx, f"{e}")
    await xx.delete()
Exemplo n.º 6
0
    def _write_product_table_row(self, work_book, work_sheet, product, line,
                                 percent_top):
        writer = ImageWriter()
        writer.set_options({
            'font_size': 18,
            'text_distance': 2,
            'quiet_zone': 2
        })
        ean = barcode.get('ean13', product.barcode, writer=writer)
        file_name = ean.save('barcode', {
            'quiet_zone': 2,
            'text_distance': 2,
            'module_height': 8
        })
        size = openpyxl.drawing.Image(file_name).image.size * array(
            [0.35, 0.35])
        img = openpyxl.drawing.Image(file_name, size=size)
        line_number = 'A%s' % line
        img.anchor(work_book.worksheets[0].cell(line_number))
        img.drawing.top = percent_top

        work_sheet.append((
            product.barcode,
            product.name,
            product.order,
            product.quantity,
        ))
        row = self._get_last_row(work_sheet)
        row.alignment = self.metadata_style
        work_sheet.append((work_sheet.add_image(img), )),
        return img.drawing.top
Exemplo n.º 7
0
def barsave():
    barcodes = barEntry.get("1.0", END)
    ean = barcode.get('ean14', barcodes, writer=ImageWriter())
    barfile_name = barfilename.get("1.0", "end-1c")
    filename = ean.save(barfile_name)
    barEntry.delete('1.0', END)
    barfilename.delete('1.0', END)
Exemplo n.º 8
0
    def __init__(self, data: BarcodeData, parent, printable):
        super().__init__(data, parent, printable)
        self.setMinimumWidth(256)

        self.combo_type = QComboBox()
        model = QStandardItemModel(0, 2)
        curr_index = 0
        for key in barcode.PROVIDED_BARCODES:
            bc = barcode.get(key)
            model.appendRow([QStandardItem(bc.name), QStandardItem(key)])
            if data.code_type == key:
                curr_index = model.rowCount() - 1

        self.combo_type.setModel(model)
        self.combo_type.setCurrentIndex(curr_index)
        self.combo_type.currentIndexChanged.connect(self.combo_type_changed)
        self.layout.addWidget(QLabel('Barcode type:'))
        self.layout.addWidget(self.combo_type)

        self.edit_text = QLineEdit(data.text, self)
        self.edit_text.textChanged.connect(self.edit_text_changed)
        self.layout.addWidget(QLabel('Value:'))
        self.layout.addWidget(self.edit_text)

        self.show_label = QCheckBox("Include label", self)
        self.show_label.setChecked(data.draw_label)
        self.layout.addWidget(self.show_label)

        self.layout.addStretch()
Exemplo n.º 9
0
 def __init__(self, text_value, barcode_type='ean13', writer=ImageWriter()):
     f = BytesIO()
     self.ean = barcode.get(barcode_type, text_value, writer=writer)
     self.ean.write(f)
     # image = self.ean.save()
     image = base64.b64encode(f.getvalue())
     self.value = image.decode('utf8')
Exemplo n.º 10
0
def genbarcode(mode, salt=0):
	#pip3 install python-levenshtein pyBarcode
	#import random, barcode
	#mode
	#1 - , 2 - goods, 3 - materialvalue, 4 - goods, 5 - , 6 - goods , 7 - , 8 - goods, 9 -
	#salt - only digit, example id
	#example
	#312365498745
	#|-first digit 3 mode materialvalue
	##|||-id materialvalue
	#####||||||||-random digit
	totallen=11
	leftlen=len(str(salt))
	a=totallen-leftlen
	randleft='1'+('0'*(a-1))
	randright='9'*a
	randdigit=random.randint(int(randleft), int(randright))
	res='%s%s%s' % (mode, salt, randdigit)
	ean = barcode.get('ean13', res)
	#print('%s - %s -> %s' % (salt, res, ean.get_fullcode()))
	return ean
	
	

	
	
def barcode_writer(directory, location, name_column, directory_pdf):
    import pandas as pd
    import barcode
    import os
    import img2pdf
    from PIL import Image
    from PIL import ImageFont
    from PIL import ImageDraw
    from barcode.writer import ImageWriter  #Diretory: Directory of the folder to save barcodes

    def fetch_data(directory,
                   column_name,
                   sheetname=0):  #Location: Directory of excel file
        #name_column: Name of the column with numbers to be barcoded
        df = pd.read_excel(
            directory,
            sheetname=0)  #directory_pdf = directory of the of pdf file.
        mylist = df[column_name].tolist()
        return mylist

    mylist = fetch_data(location, name_column)
    #mylist2 = fetch_data(location, "Bata")
    mylist3 = []
    mylist4 = []

    for data in mylist:
        data = str(data)
        ean = barcode.get('ean8', data, writer=ImageWriter())
        ean.default_writer_options['module_height'] = 3.0
        ean.default_writer_options['text_distance'] = 1.0
        directory3 = directory + "/{}"
        filename = ean.save(directory3.format(data))
        mylist3.append(filename)
Exemplo n.º 12
0
def agregarproductos(request):
	if request.method == 'POST':
		try:
			campo = 'Debe seleccionar categoria'
			pcategoria = int(request.POST.get('categoria'))
			campo = 'Debe seleccionar precio'
			pprecio = int(request.POST.get('precio'))
			campo = 'Debe ingresar nombre para el producto'
			pnombre = request.POST.get('nombre')
			pcategoria = Categoria.objects.get(id = pcategoria)
			pprecio = Precio.objects.get(id = pprecio)
			producto = Producto(nombre = pnombre, categoria = pcategoria, precio = pprecio)
			producto.save()
			barra = str(producto.id).zfill(12)
			barra = barcode.get('ean13', barra)
			producto.barras = barra
			producto.save()
			respuesta = "Producto registrado correctamente."
		except ValueError:
			respuesta = "Error: "
			respuesta =respuesta + campo
		except Exception as ex:
			respuesta = str(ex.message)
		finally:
			return HttpResponse(
				json.dumps(respuesta), 
				content_type="application/json"
			) 
Exemplo n.º 13
0
def barcode(message):
    input_str = extract_args(message)
    usage = get_translation('barcodeUsage', ['**', '`'])
    reply = message.reply_to_message
    if len(input_str) < 1 and not reply:
        edit(message, usage)
        return
    edit(message, f'`{get_translation("processing")}`')
    if reply:
        if reply.media:
            downloaded_file_name = download_media_wc(reply)
            media_list = None
            with open(downloaded_file_name, 'rb') as file:
                media_list = file.readlines()
            qrmsg = ''
            for media in media_list:
                qrmsg += media.decode('UTF-8') + '\r\n'
            remove(downloaded_file_name)
        else:
            qrmsg = reply
    else:
        qrmsg = input_str

    bar_code_type = 'code128'
    try:
        bar_code_mode_f = get(bar_code_type, qrmsg, writer=ImageWriter())
        filename = bar_code_mode_f.save(bar_code_type)
        reply_doc(message, filename, delete_after_send=True)
    except Exception as e:
        edit(message, str(e))
        return
    message.delete()
Exemplo n.º 14
0
def createLabel(serial_number, fulltext_name, location):
    fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 25)

    code128 = barcode.get('code128',
                          serial_number,
                          writer=barcode.writer.ImageWriter())
    barcode_image = code128.render().resize((300, 120)).crop((0, 0, 300, 80))

    label = Image.new('1', (696, 120), color=1)
    label.paste(barcode_image, box=(0, 0))

    lines = textwrap.wrap(fulltext_name[:75], width=25)
    y_text = 5

    text = ImageDraw.Draw(label)

    for line in lines:
        width, height = fnt.getsize(line)
        text.text((320, y_text), line, font=fnt, fill=0)
        y_text += height

    text.text((65, 93), serial_number, font=fnt, fill=0)
    text.text((320, 95), location, font=fnt, fill=0)
    text.text((660, 10), "J", font=fnt, fill=0)
    text.text((660, 45), "M", font=fnt, fill=0)
    text.text((660, 80), "W", font=fnt, fill=0)

    return label
Exemplo n.º 15
0
    def create(self, vals):
        res = super(productproduct, self).create(vals)
        number_random = 0
        if res:
            if not vals.get(
                    'barcode') and self.env['ir.config_parameter'].sudo(
                    ).get_param('bi_generate_product_ean13.gen_barcode'):
                if self.env['ir.config_parameter'].sudo().get_param(
                        'bi_generate_product_ean13.generate_option') == 'date':
                    barcode_str = self.env[
                        'barcode.nomenclature'].sanitize_ean(
                            "%s%s" %
                            (res.id, datetime.now().strftime("%d%m%y%H%M")))
                else:
                    number_random = int("%0.13d" %
                                        random.randint(0, 999999999999))
                    barcode_str = self.env[
                        'barcode.nomenclature'].sanitize_ean("%s" %
                                                             (number_random))
                ean = barcode.get('ean13', barcode_str, writer=ImageWriter())
                #                 path  =  os.path.abspath('bi_generate_product_ean13')
                filename = ean.save('/tmp/ean13')
                f = open(filename, 'rb')
                jpgdata = f.read()
                imgdata = base64.encodestring(jpgdata)
                res.write({'barcode': barcode_str, 'barcode_img': imgdata})
                os.remove(filename)

        return res
Exemplo n.º 16
0
Arquivo: prnt.py Projeto: kumike/brcdp
def makecodes(*args):
    sufix = 0
    for i in args[0]:
        try:
            ean = barcode.get('ean13', str(i), writer=ImageWriter())
            ean.default_writer_options['text_distance'] = 2
            ean.default_writer_options['font_size'] = 18
            ean.default_writer_options['quiet_zone'] = 6.5
            #ean.default_writer_options['background'] = 'red'
            ### назначаем текст если опция тру
            if text is not None:
                ean.default_writer_options['write_text'] = False
                ean.default_writer_options['text'] = text
                if len(text) > 23:
                    exit(
                        'Текста должно быть не больше 23 символа включая пробелы!'
                    )
            fname = ean.save('barcode0' + str(sufix))
            sufix += 1
        except barcode.errors.NumberOfDigitsError:
            exit('Это EAN13 штрихкод! нужно токо 12 цифр! небольше неменьше!')
        except barcode.errors.IllegalCharacterError:
            exit(
                'EAN13 штрихкод может содержать только цифрЫ!!не больше 12 знаков!'
            )
Exemplo n.º 17
0
 def handle_(self, para):
     setui.handle_(self, para)
     #        self.rect.arg=self.data
     ean = barcode.get('UPCA', para['text'], writer=ImageWriter())
     self.rect.picpath = para['text']
     filename = ean.save(self.rect.picpath, self.data)
     self.rect.SetPicPath(para['text'] + '.png')
Exemplo n.º 18
0
 def image(self, shape=None):
     """Returns image representation of barcode.
     
     Args:
         shape: desired image shape.
     
     Returns:
         An numpy array image representation of barcode.
     """
     # Convert code to StringIO to Image to Numpy array.
     ean = barcode.get('ean', self.code, writer=barcode.writer.ImageWriter())
     str_io = StringIO.StringIO()
     ean.write(str_io)
     str_io.seek(0)
     im = np.array(Image.open(str_io).convert('RGB'))[:,:,::-1]
     # Reshape (if necessary) and pad (if necessary).
     if shape != None:
         scaling = min(1.0*shape[0]/im.shape[0], 1.0*shape[1]/im.shape[1])
         unpadded_shape = np.min((np.array(im.shape[:2])*scaling, shape), axis=0).astype(int)
         im = cv2.resize(im, tuple(unpadded_shape[::-1]))
         bottom = (shape[0] - im.shape[0])/2
         top = shape[0]-im.shape[0]-bottom
         right = (shape[1] - im.shape[1])/2
         left = shape[1]-im.shape[1]-right
         im = cv2.copyMakeBorder(im, top, bottom, left, right,
                                 borderType=cv2.BORDER_CONSTANT, value=(255,255,255))
     return im
Exemplo n.º 19
0
def print_barcode(barcode_Name):
    Code_128 = "code128"
    ean = barcode.get(Code_128, barcode_Name, writer=ImageWriter())
    f = ean.save(os.getcwd() + "\\" + barcode_Name)
    sk_image = imread(f)
    image = img_as_ubyte(sk_image)
    return image
Exemplo n.º 20
0
def generate_barcode(request):
    stds = SigningSession.objects.all().values_list('student')
    print(stds)
    for i, std in enumerate(stds):
        bc = barcode.get('code128', std[0])
        bc.save("/home/yezy/Desktop/.security/sss/barcode" + str(i))
    return HttpResponse("All barcodes generated!..")
Exemplo n.º 21
0
 async def _barcode(self, ctx, type_code, *, content):
     try:
         types = [
             'ean8', 'ean13', 'ean14', 'code128', 'code39', 'pzn', 'issn',
             'isbn13', 'isbn10', 'jan', 'upca'
         ]
         if type_code.lower() not in types:
             await warn(
                 ctx=ctx,
                 content=
                 f'바코드의 타입을 찾을 수 없습니다.\n타입 목록:\n```{", ".join([i.upper() for i in types])}```'
             )
         img = get(type_code.lower(), content, writer=ImageWriter())
         file = img.save(type_code)
         await ctx.send(file=discord.File(file))
         remove(file)
     except Exception as error:
         if str(error).endswith('ISBN must start with 978 or 979.'):
             return await warn(ctx=ctx,
                               content='이 타입은 코드가 978이나 979로 시작해야 합니다')
         elif str(error).endswith('can only contain numbers.'):
             return await warn(ctx=ctx, content='이 타입은 코드에 숫자만 들어갈 수 있습니다.')
         elif str(error).endswith(
                 'Command raised an exception: NumberOfDigitsError:'):
             return await warn(ctx=ctx, content='내용의 글자 수가 올바르지 않습니다')
         else:
             return await warn(ctx=ctx, content='저런! 에러가 발생했습니다.')
Exemplo n.º 22
0
 def generate_barcode(self):
     webnotes.errprint([self.doc.naming_series])
     # self.doc.patient_online_id=self.doc.name
     # from barcode.writer import ImageWriter
     # ean = barcode.get('code39','123322ABS232')
     # webnotes.errprint(ean)
     # path = os.path.join(get_base_path(), "public", "barcode_img")+"/"+self.doc.name
     # fullname = ean.save(path)
     # barcode_img = '<html>\
     #         <table style="width: 100%; table-layout: fixed;">\
     #                 <tr>\
     #                         <td style="width:510px">\
     #                                 <img src="'"/barcode_img/"+self.doc.name+".png"'" width="200px">\
     #                         </td>\
     #                 </tr>\
     #         </table>\
     # </html>'
     #s="23232ASA343222"
     s=self.doc.name
     import barcode
     from barcode.writer import ImageWriter
     ean = barcode.get('code39', s, writer=ImageWriter())
     path = os.path.join(get_base_path(), "public", "barcode_img")+"/"+s
     filename = ean.save(path)
     barcode_img = '<html>\
                     <table style="width: 100%; table-layout: fixed;">\
                         <tr>\
                             <td style="width:510px">\
                                 <img src="'"../barcode_img/"+s+".png"'" width="200px">\
                             </td>\
                         </tr>\
                     </table>\
                 </html>'
     self.doc.barcode_image = barcode_img
     self.doc.save()
Exemplo n.º 23
0
async def bq(event):
    """ For .barcode command, genrate a barcode containing the given content. """
    await event.edit("`Processing..`")
    input_str = event.pattern_match.group(1)
    message = "SYNTAX: `.barcode <long text to include>`"
    reply_msg_id = event.message.id
    if input_str:
        message = input_str
    elif event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        reply_msg_id = previous_message.id
        if previous_message.media:
            downloaded_file_name = await event.client.download_media(previous_message)
            m_list = None
            with open(downloaded_file_name, "rb") as fd:
                m_list = fd.readlines()
            message = ""
            for m in m_list:
                message += m.decode("UTF-8") + "\r\n"
            os.remove(downloaded_file_name)
        else:
            message = previous_message.message
    else:
        return event.edit("SYNTAX: `.barcode <long text to include>`")

    bar_code_type = "code128"
    try:
        bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter())
        filename = bar_code_mode_f.save(bar_code_type)
        await event.client.send_file(event.chat_id, filename, reply_to=reply_msg_id)
        os.remove(filename)
    except Exception as e:
        return await event.edit(str(e))
    await event.delete()
Exemplo n.º 24
0
    def generate_barcode(self, card_type):
        codes = Barcode.objects.filter(student=self)
        for code in codes:
            if code.card_type == card_type:
                return code.code

        # prefix to tell which type of card we are creating
        prefix = {1:'R',2:'C',3:'S',4:'L',5:'A'}

        bcode_string = prefix[card_type] + \
                self.first_name[:10] + self.last_name[:10] + \
                "%05d" % self.id
        bcode = barcode.get('code39',bcode_string)
        filename = bcode.save(bcode.get_fullcode())

        code = Barcode(student=self,code=bcode.get_fullcode(),
            code_loc=filename)
        code.save()

        # move image to correct directory
        loc = 'img/barcodes/' + filename
        dst = os.path.join(STATIC_ROOT, loc)
        os.rename(filename,dst)

        return code.code
Exemplo n.º 25
0
def print_from_id(request):
    sum = 0
    p_id = request.POST.get('id')
    num = random.randrange(12345678910234)
    num = str(num)
    if len(str(num)) == 11:
        num = str(num) + 1
        num = int(num)
    else:
        num = num

    ean = barcode.get('ean13', str(num), writer=ImageWriter())
    filename = ean.save('ean13')
    file = open('/home/budescode/inventory/project/static/images/barcode.png',
                'wb')
    ean.write(file)
    cartitems = get_object_or_404(CartItems, cart_id=p_id)
    cart = Cart.objects.filter(cartit=cartitems)
    template = get_template('Administrator/print_from_id.html')
    context = {'cartitems': cartitems, 'cart': cart}
    #return render (request, 'Administrator/order.html', context)
    html = template.render(context)
    pdf = render_to_pdf('Administrator/print_from_id.html', context)
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')

        filename = "%s_receipt.pdf" % ('1k-clothes')
        content = "inline; filename=%s" % (filename)
        download = request.GET.get("download")
        if download:
            content = "attachment; filename='%s'" % (filename)
        response['Content-Disposition'] = content
        return response
    return HttpResponse("Not found")
Exemplo n.º 26
0
def barcode_displayer(displayed_code: str) -> None:
    try:
        epd = epd2in9.EPD()

        epd.init(epd.lut_full_update)
        epd.Clear(0xFF)
        
        ean = barcode.get('code39', displayed_code, writer = barcode.writer.ImageWriter())
        image = ean.render()

        epd.display(epd.getbuffer(image.resize((epd.height, epd.width))))

        time.sleep(1)

    except IOError as e:
        logging.info(e)
        
    except KeyboardInterrupt:    
        logging.info("ctrl + c:")
        epd2in9.epdconfig.module_exit()
        exit()

    except Exception as e:
        logging.info(str(e))

    finally:
        epd.Clear(0xFF)
Exemplo n.º 27
0
    def create_image_full(self, img_name, bc, name, details, width, height,
                          h_num, v_num):
        def mm2px(mm, dpi=300):
            return math.floor((mm * dpi) / 25.4)

        #bc.png
        bc_object = barcode.get('ean13',
                                bc,
                                writer=writer.ImageWriter(width, height / 3))
        svg = bc_object.save('bc')
        #top
        txt_size = int(mm2px(3))
        font = ImageFont.truetype('andlso.ttf', txt_size)
        img = Image.new(
            "RGBA", (int(mm2px(width * h_num)), int(mm2px(height * v_num))),
            (255, 255, 255))
        draw = ImageDraw.Draw(img)
        reshaped_text = get_display(arabic_reshaper.reshape(unicode(name)))
        # draw.text((80, 50), reshaped_text, (0, 0, 0), font=font)
        y_text = 0
        lines = textwrap.wrap(reshaped_text, width=30)
        for line in lines:
            ww, hh = font.getsize(line)
            draw.text((40, y_text), line, (0, 0, 0), font=font)
            y_text += hh
        #price part
        pf = ImageFont.truetype('andlso.ttf', int(mm2px(3)))
        # draw.text((375,175), price, (0, 0, 0), font=pf)
        txt_price = Image.new('RGBA', (500, int(mm2px(4))), (255, 255, 255))
        d = ImageDraw.Draw(txt_price)
        d.text((0, 0), bc, (0, 0, 0), font=pf)

        #details part
        details_text = get_display(arabic_reshaper.reshape(unicode(details)))

        #bc image
        im2 = Image.open(svg)
        #draw section
        if v_num == 2:
            img.paste(txt_price,
                      box=(int(mm2px((width / 2))), int(mm2px(
                          (height * 2) / 3))))
            draw.text((10, int(mm2px((height * 2) / 3))),
                      details_text, (0, 0, 0),
                      font=font)
        else:
            img.paste(txt_price, box=(40, int(mm2px((height * 2) / 3))))
            draw.text((40, int(mm2px((height * 2.5) / 3))),
                      details_text, (0, 0, 0),
                      font=font)
        img.paste(im2, box=(-40, int(mm2px(height / 3))))
        img.save("thumb/%s.png" % (img_name))
        img.paste(img, box=(0, int(mm2px(height))))
        img.save("thumb/%s.png" % (img_name))

        #empty image
        img3 = Image.new("RGBA", (int(mm2px(width)), int(mm2px(height))),
                         (255, 255, 255))
        img3.save('empty.png')
Exemplo n.º 28
0
def genera_barcode(codigo, filename):
    options = dict(dpi=300,
                   module_height=6,
                   center_text=True,
                   text_distance=1,
                   font_size=6)
    ean = barcode.get('ean13', codigo, writer=ImageWriter())
    return ean.save(filename, options)
Exemplo n.º 29
0
 def add_barcode(self, data, x, y, width=100, height=50):
     output_fd = tempfile.NamedTemporaryFile(dir=settings.FILE_UPLOAD_TEMP_DIR, suffix='', mode='wb',
                                             prefix='pigi1300-copy-barcode-', delete=True)
     output_fd.close()
     ean = barcode.get('ean13', data, writer=ImageWriter())
     filename = ean.save(output_fd.name)
     self.temp_files_to_remove.append(filename)
     self.current_page_canvas.drawImage(filename, x, y, width=width, height=height, mask='auto', anchor='sw')
Exemplo n.º 30
0
def barcode_image(request, pk):
    ms = Master.objects.get(pk=pk)
    bc = ms.barcode

    io = StringIO()
    code39 = barcode.get('code39', bc)
    code39.write(io)
    return HttpResponse(io.getvalue(), mimetype='image/svg+xml')
Exemplo n.º 31
0
async def barcode_image(barcode_gen: Barcode):
    message_filename = "./barcode/" + barcode_gen.barcode_message

    ean = barcode.get(barcode_gen.barcode_type,
                      barcode_gen.barcode_message,
                      writer=ImageWriter())
    filename = ean.save(message_filename)
    return FileResponse(filename)
Exemplo n.º 32
0
def create_barcode(p_bc):
    len_bc = len(p_bc)
    if len_bc < LENGHT_BC:
        p_bc += (LENGHT_BC - len_bc) * "0"
    name = str(p_bc)
    ean = barcode.get('ean13', str(p_bc), writer=barcode.writer.ImageWriter())
    filename = ean.save(name)
    return name, int(ean.ean)
Exemplo n.º 33
0
    def generate(self, string, filename):

        file = os.path.join(os.path.dirname(__file__), "../barcodes",
                            f"{filename}")
        # or sure, to an actual file:
        ean = barcode.get("Code128", f"{string}", writer=ImageWriter())
        filename = ean.save(file, options={"write_text": False})
        return filename
Exemplo n.º 34
0
def show_barcode(message, tekUser):
#     EAN = barcode.get_barcode_class('ean13')
#     ean = EAN(tekUser.karta, writer=ImageWriter())
    try:
        barCodeImage_ = barcode.get('ean13', tekUser.karta, writer=ImageWriter())
        barCodeImage_.save(pth+str(tekUser.chat_id))
    except:
        tekUser.Last_message = bot.send_message(message.chat.id,'Неможливо відобразити штрихкод')
Exemplo n.º 35
0
def bargenerate():
    if len(Subject.get()) != 0 and Subject.get() != "Enter subject here":
        global brcode, fpath, ogpath
        brcode = barcode.get("code128", Subject.get(), writer=ImageWriter())
        brcodesvg = barcode.get("code128", Subject.get())
        ogpath = os.getcwd()
        dummy = "src"
        if not os.path.exists(dummy):
            os.makedirs(dummy)
        fpath = os.path.join(dummy, Subject.get())
        brcode.save(fpath)
    else:
        messagebox.showinfo("", "Please Enter some Subject")
    try:
        showbrcode()
    except:
        pass
Exemplo n.º 36
0
async def _(event):
    if event.fwd_from:
        return
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if event.is_group:
        if await is_register_admin(event.input_chat, event.message.sender_id):
            pass
        elif event.chat_id == iid and event.sender_id == userss:
            pass
        else:
            return
    start = datetime.now()
    input_str = event.pattern_match.group(1)
    message = "SYNTAX: `.barcode <long text to include>`"
    reply_msg_id = event.message.id
    if input_str:
        message = input_str
    elif event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        reply_msg_id = previous_message.id
        if previous_message.media:
            downloaded_file_name = await event.client.download_media(
                previous_message,
                Config.TEMP_DOWNLOAD_DIRECTORY,
            )
            m_list = None
            with open(downloaded_file_name, "rb") as fd:
                m_list = fd.readlines()
            message = ""
            for m in m_list:
                message += m.decode("UTF-8") + "\r\n"
            os.remove(downloaded_file_name)
        else:
            message = previous_message.message
    else:
        message = "SYNTAX: `/barcode <long text to include>`"
    bar_code_type = "code128"
    try:
        bar_code_mode_f = barcode.get(bar_code_type,
                                      message,
                                      writer=ImageWriter())
        filename = bar_code_mode_f.save(bar_code_type)
        await event.client.send_file(
            event.chat_id,
            filename,
            caption=message,
            reply_to=reply_msg_id,
        )
        os.remove(filename)
    except Exception as e:
        await event.reply(str(e))
        return
    end = datetime.now()
    ms = (end - start).seconds
    await event.reply("Created BarCode in {} seconds".format(ms))
Exemplo n.º 37
0
def make_barcode_png(data, **options):
    barcodefile = StringIO()

    code128 = barcode.get('code128', data, writer=ImageWriter())
    # Sizes here are the ones used in the PDF
    code128.write(barcodefile, {'write_text': False, 'module_height': 8})
    barcodefile.seek(0)

    return barcodefile
Exemplo n.º 38
0
def pin_result(request, hash):
    today = date.today()
    pin = get_object_or_404(Credential, credential_hash=hash, is_valid=True, expired__gte=today)
    import barcode
    from io import BytesIO
    from barcode.writer import ImageWriter
    code = barcode.get(settings.BARCODE_TYPE, pin.credential_no, writer=ImageWriter())
    output = BytesIO()
    image = code.render(None)
    image.save(output, format='PNG')
    return render_to_response('pin_result.html', {
        'barcode': b64encode(output.getvalue()),
    })
Exemplo n.º 39
0
  def _obtener_codigos( self, cr, uid, lista ) :
    """
    Metodo que obtiene la informacion del producto
    * Argumentos OpenERP: [cr]
    @param lista:
    @return string
    """
    listado = lista.split('\n')
    valores = '\n'
    fecha = time.strftime("%y%m%d")
    fecha_imp = time.strftime('%d/%m/%y')
    # time.strftime('%d %b %y'))   %d/%m/%Y
    if ( type( listado ) in ( list, tuple ) ):
      #se eliminan los datos de la tabla listado antes de insertar
      cr.execute(
        """
        DELETE FROM listado_codigo
        """
      )
      #se recorre el listado
      for codigo in listado:

        #Crea el codigo de Barras
        ean = barcode.get('ean13', codigo, writer=barcode.writer.ImageWriter())
        # Genera el archivo
        ruta = '/opt/openerp/server/openerp/addons/codigos/img/'+ str('ean_' + codigo )
        f = open(ruta , 'wb')
        #se crea la imagen y se guarda en la ruta especificada
        almacena = ean.write(f)
        
        #si no encuentra el producto insertar
        no_encontrado = ('NO ENCONTRADO', codigo, 0.0, ruta, fecha, '0.00', str(fecha_imp) )
        #se ejecuta la consulta en la tabla productos
        cr.execute(
        """
          SELECT upper(name), ean13, list_price  
          FROM product_template t
          INNER JOIN product_product p
          ON t.id = p.product_tmpl_id
          WHERE ean13 =%s
        """,(codigo,)
        )
        resultado = cr.fetchone()
        valores = (( resultado[0], resultado[1], (resultado[2]), ruta, fecha, (str(resultado[2])+'0'), str(fecha_imp) )) if type( resultado ) in ( list, tuple ) and resultado != None else no_encontrado
        #se insertan los nuevos datos a la tabla
        cr.execute('INSERT INTO listado_codigo (descripcion, cod_barras, precio, ruta_codigo, fecha, precio_str, fecha_str ) VALUES (%s::varchar(24), %s, %s, %s, %s, %s, %s)',
                     valores )
      return True
    else :
      return False
Exemplo n.º 40
0
 def barcode_svg(self, barcode_format, barcode_string):
     """
     accepts
         barcode_format <str> one of ['code39', 'ean', 'ean13', 'ean8', 'gs1', 'gtin', 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca']
         barcode_string <str> string constructed according to barcode_format requirements - see google, svp
     """
     try:
         barcode_svg = barcode.get(
                 barcode_format,
                 barcode_string).render(writer_options=None)
     except Exception as error:
         return {
                 "error": 500,
                 "message": str(error)
                 }
     return {"barcode_svg": barcode_svg} 
Exemplo n.º 41
0
def format_inline_barcode(data):
    barcodefile = StringIO()

    # data is written into the SVG without a CDATA, so base64 encode it
    code128 = barcode.get('code128', data, writer=SVGWriter())
    code128.write(barcodefile, {'write_text': False})
    barcodefile.seek(0)

    root = etree.XML(barcodefile.read())
    # Allow us to scale it with CSS
    root.attrib['viewBox'] = '0 0 %s %s' % (root.attrib['width'], root.attrib['height'])
    del root.attrib['width']
    del root.attrib['height']
    root.attrib['preserveAspectRatio'] = 'none'

    return Markup(etree.tostring(root))
Exemplo n.º 42
0
def paypal(quantity, event_id, tracker):
    if request.method == 'POST':
        global gtracker
        if tracker != gtracker:
            return bad_state()
        nonce_from_the_client = request.form["payment_method_nonce"]
        result = braintree.Transaction.sale({
            "amount": "10.00",
            "payment_method_nonce": nonce_from_the_client,
            "options": {
              "submit_for_settlement": True
            }
        })
        if result.is_success:
            transaction = result.transaction
            print transaction
            newTicket = Ticket(quantity=quantity, user_id=login_session['user_id'], event_id=event_id, pp_transaction=result.transaction.id)
            session.add(newTicket)
            activity = ''
            activity += str(quantity) + ' tickets bought by ' + login_session['email']
            newLog = Log(timestamp= datetime.datetime.today(), user_id= 0, activity=activity)
            session.add(newLog)
            session.commit()
            ean = barcode.get('code39', result.transaction.id, writer=ImageWriter())
            barcode_filename = ean.save(UPLOAD_FOLDER + result.transaction.id+"_barcode")
            short_filename = result.transaction.id+"_barcode"
            event = session.query(Event).filter_by(id=event_id).one()
            msg = Message("Your Tickets", sender=MAIL_DEFAULT_SENDER, recipients=[login_session['email']])
            print short_filename
            with app.open_resource(barcode_filename[2:]) as fp:
                msg.attach(short_filename+".png", short_filename+"/png", fp.read())
            text = render_template("Ticket.txt",  newTicket=newTicket, event=event, barcode_filename=short_filename)
            html = render_template("Ticket.html", newTicket=newTicket, event=event, barcode_filename=short_filename)
            send_ticket(text_body=text, html_body=html, msg=msg)
        else:
            print [error.code for error in result.errors.all]
        
        flash('Tickets Purchased')
        return redirect(url_for('main_page'))
    else:
        if('username' not in login_session):
            flash('You must login to buy a ticket')
            return redirect(url_for('login'))
        client_token =  braintree.ClientToken.generate()
        event = session.query(Event).filter_by(id=event_id).one()
        resp = make_response(render_template('paypal.html', paypal_client_token = client_token, quantity=quantity, event=event))
        return resp
Exemplo n.º 43
0
	def generate_barcode(self):
		# webnotes.errprint([self.doc.naming_series])
                self.doc.patient_online_id=self.doc.name
                from barcode.writer import ImageWriter
                ean = barcode.get('code39',self.doc.patient_online_id,writer=ImageWriter())
                path = os.path.join(get_base_path(), "public", "barcode_img")+"/"+self.doc.name
		fullname = ean.save(path)
		barcode_img = '<html>\
			<table style="width: 100%; table-layout: fixed;">\
				<tr>\
					<td style="width:510px">\
						<img src="'"/barcode_img/"+self.doc.name+".png"'" width="200px">\
					</td>\
				</tr>\
			</table>\
		</html>'
		self.doc.barcode_image = barcode_img
Exemplo n.º 44
0
	def on_update(self):
		#ebnotes.errprint("s")
		#ebnotes.errprint(self.doc.name)
		s='232242342'
		s=self.doc.name
                #webnotes.errprint(s)
		import barcode
                from barcode.writer import ImageWriter
                ean = barcode.get('code39',s, writer=ImageWriter())
                path = os.path.join(get_base_path(), "public", "barcode_img")+"/"+s
                filename = ean.save(path)
                barcode_img = '<html>\
                        <table>\
                                  <tr>\
                                          <td >\
                                                  <img src="'"../barcode_img/"+s+".png"'" width="300px">\
                                          </td>\
                                  </tr>\
                          </table>\
                  </html>'
                self.doc.barcode_image = barcode_img
                #self.doc.img_dtl="<img src='../barcode_img/zzz.png' alt='Smiley face' height='80' width='300'>".replace('zzz',self.doc.name)
                self.doc.save()
Exemplo n.º 45
0
def fnbarcode(barcod):
    ean = barcode.get('ean13',barcod)
    global imgpath
    imgpath = ean.save("/tmp/"+barcod)
    return imgpath
Exemplo n.º 46
0
 def _obtener_codigos( self, cr, uid, lista ) :
   """
   Metodo que obtiene la informacion del producto y el codigo de barras apartir del codigo del producto e inserta los datos en la tabla listado.
   * Argumentos OpenERP: [cr]
   @param lista: lista de codigos
   @return bool
   """
   listado = lista.split()
   valores = ' '
   fecha = time.strftime("%y%m%d")
   fecha_imp = time.strftime('%d/%m/%y')
   if ( type( listado ) in ( list, tuple ) ):
     #se eliminan los datos de la tabla listado antes de insertar
     cr.execute(
       """
       DELETE FROM listado_codigo WHERE create_uid=%s
       """,(uid,)
     )
     #se recorre el listado
     for codigo in listado:
       if codigo.isdigit() == True:
         if len(codigo) != 13:
           nombre_produc ='NO ES EAN-13'
           raise osv.except_osv(_( 'Aviso' ),_( 'El código debe contener 13 números sin espacios entre cada dígito' ) )
         else :
           nombre_produc = 'NO ENCONTRADO'
       else :
         raise osv.except_osv(_( 'Aviso!' ),_( 'El código sólo debe contener números' ) )
       #Crea el codigo de Barras
       ean = barcode.get('ean13', codigo, writer=barcode.writer.ImageWriter())
       # Genera el archivo
       ruta = '/tmp/ean_'+ str(codigo)
       f = open(ruta , 'wb')
       #se crea la imagen y se guarda en la ruta especifica
       almacena = ean.write(f)
       #si no encuentra el producto insertar
       no_encontrado = (nombre_produc, codigo, 0.0, ruta, fecha, '0.00', str(fecha_imp), uid, 'No' )
       #se ejecuta la consulta en la tabla productos
       cr.execute(
       """
         SELECT upper(name), ean13, list_price, default_code  
         FROM product_template t
         INNER JOIN product_product p
         ON t.id = p.product_tmpl_id
         WHERE p.active = true and
         ean13 = %s
         order by p.id desc
         limit 1
       """,(codigo,)
       )
       resultado = cr.fetchone()
       #se valida que el precio tenga decimales
       num = 0
       decimales =''
       precio=[]
       if resultado != None and type( resultado ) in ( list, tuple ) and resultado[2] != 0 :
         p = str(resultado[2])
         precio=p.split(".")
         decimales = str(precio[1])
         num = len(decimales)
       valores = (
                   ( resultado[0], resultado[1], (resultado[2]), ruta, fecha,
                    (
                     ( resultado[2] ) if num == 2 and precio[1] > 9  else (str(resultado[2])+'0')), str(fecha_imp),uid, resultado[3]
                    )
                   if type( resultado ) in ( list, tuple ) and resultado != None else no_encontrado
                 )
       #se insertan los nuevos datos a la tabla listado_codigo
       cr.execute(
         """
         INSERT INTO listado_codigo
         (descripcion, cod_barras, precio, ruta_codigo, fecha, precio_str, fecha_str, create_uid, referencia )
         VALUES (%s::varchar(24), %s, %s, %s, %s, %s, %s, %s, %s)
         """, valores )
     return True
   else :
     return False
Exemplo n.º 47
0
def createBarcode(number, name): 
    path = '/Users/nicholaslamprecht/GitHub/nictec_website2.0/nictecsite/storage/static/storage/Barcodes/'
    f = open(path + name, 'wb')
    code = barcode.get('code39', number, writer=ImageWriter())
    code.write(f) 
    return
def do_process_workbook():
    # this is called as a background thread to ensure the interface is responsive
    print_if_debug("creating temp directory")
    if not args.keep_barcodes_in_cwd:
        tempdir = tempfile.mkdtemp()
    else:
        temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images')
        os.mkdir(temp_dir_in_cwd)
        tempdir = temp_dir_in_cwd
    print_if_debug("temp directory created as: " + tempdir)
    progress_bar.configure(mode='indeterminate', maximum=100)
    progress_bar.start()
    progress_numbers.configure(text="opening workbook")
    wb = openpyxl.load_workbook(old_workbook_path)
    ws = wb.worksheets[0]
    progress_numbers.configure(text="testing workbook save")
    wb.save(new_workbook_path)
    count = 0
    save_counter = 0
    progress_bar.configure(maximum=ws.max_row, value=count)
    progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
    border_size = int(border_spinbox.get())

    for _ in ws.iter_rows():  # iterate over all rows in current worksheet
        if not process_workbook_keep_alive:
            break
        try:
            count += 1
            progress_bar.configure(maximum=ws.max_row, value=count, mode='determinate')
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
            progress_bar.configure(value=count)
            # get code from column selected in input_colum_spinbox, on current row,
            # add a zeroes to the end if option is selected to make seven or 12 digits
            print_if_debug("getting cell contents on line number " + str(count))
            upc_barcode_string = str(ws[input_column_spinbox.get() + str(count)].value)
            print_if_debug("cell contents are: " + upc_barcode_string)
            if not upc_barcode_string == '':
                if barcode_type_variable.get() == "ean13" or barcode_type_variable.get() == "ean8":
                    try:
                        _ = int(upc_barcode_string)  # check that "upc_barcode_string" can be cast to int
                    except ValueError:
                        raise ValueError("Cell contents are not an integer, skipping")
                # select barcode type, specify barcode, and select image writer to save as png
                if barcode_type_variable.get() == "ean8":
                    if pad_ean_option.get() is True:
                        if len(upc_barcode_string) < 6:
                            upc_barcode_string = upc_barcode_string.rjust(6, '0')
                        if len(upc_barcode_string) <= 7:
                            upc_barcode_string = upc_barcode_string.ljust(7, '0')
                        else:
                            raise ValueError("Cell contents are more than 7 characters, skipping row")
                    else:
                        if len(upc_barcode_string) != 7:
                            raise ValueError("Cell contents are not 7 characters, skipping row")
                elif barcode_type_variable.get() == "ean13":
                    if pad_ean_option.get() is True:
                        if len(upc_barcode_string) < 11:
                            upc_barcode_string = upc_barcode_string.rjust(11, '0')
                        if len(upc_barcode_string) <= 12:
                            upc_barcode_string = upc_barcode_string.ljust(12, '0')
                        else:
                            raise ValueError("Cell contents are more than 12 characters, skipping row")
                    else:
                        if len(upc_barcode_string) != 12:
                            raise ValueError("Cell contents are not 12 characters, skipping row")
                elif barcode_type_variable.get() == "code39":
                    upc_barcode_string = upc_barcode_string.upper()
                    upc_barcode_string = re.sub('[^A-Z0-9./*$%+\- ]+', ' ', upc_barcode_string)
            else:
                raise ValueError("Cell is empty, skipping row")

            ean = barcode.get(barcode_type_variable.get(), upc_barcode_string, writer=ImageWriter())
            # select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file.
            # dpi is the conversion from svg image size in mm, to what the image writer thinks is inches.
            ean.default_writer_options['dpi'] = int(dpi_spinbox.get())
            # module height is the barcode bar height in mm
            ean.default_writer_options['module_height'] = float(height_spinbox.get())
            # text distance is the distance between the bottom of the barcode, and the top of the text in mm
            ean.default_writer_options['text_distance'] = 1
            # font size is the text size in pt
            ean.default_writer_options['font_size'] = int(font_size_spinbox.get())
            # quiet zone is the distance from the ends of the barcode to the ends of the image in mm
            ean.default_writer_options['quiet_zone'] = 2
            # save barcode image with generated filename
            print_if_debug("generating barcode image")
            with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file_path:
                filename = ean.save(initial_temp_file_path.name[0:-4])
                print_if_debug("success, barcode image path is: " + filename)
                print_if_debug("opening " + str(filename) + " to add border")
                barcode_image = pil_Image.open(str(filename))  # open image as pil object
                print_if_debug("success")
                print_if_debug("adding barcode and saving")
                img_save = pil_ImageOps.expand(barcode_image, border=border_size,
                                               fill='white')  # add border around image
                width, height = img_save.size  # get image size of barcode with border
                # resize cell to size of image
                ws.column_dimensions[output_column_spinbox.get()].width = int(math.ceil(float(width) * .15))
                ws.row_dimensions[count].height = int(math.ceil(float(height) * .75))
                # write out image to file
                with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path:
                    img_save.save(final_barcode_path.name)
                    print_if_debug("success, final barcode path is: " + final_barcode_path.name)
                    # open image with as openpyxl image object
                    print_if_debug("opening " + final_barcode_path.name + " to insert into output spreadsheet")
                    img = OpenPyXlImage(final_barcode_path.name)
                    print_if_debug("success")
                    # attach image to cell
                    print_if_debug("adding image to cell")
                    # add image to cell
                    ws.add_image(img, anchor=output_column_spinbox.get() + str(count))
                    save_counter += 1
            print_if_debug("success")
        except Exception as barcode_error:
            print_if_debug(barcode_error)
        # This save in the loop frees references to the barcode images,
        #  so that python's garbage collector can clear them
        if save_counter >= file_limit - 50:
            print_if_debug("saving intermediate workbook to free file handles")
            progress_bar.configure(mode='indeterminate', maximum=100)
            progress_bar.start()
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row) + " saving")
            wb.save(new_workbook_path)
            print_if_debug("success")
            save_counter = 1
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
    progress_bar.configure(value=0)
    print_if_debug("saving workbook to file")
    progress_bar.configure(mode='indeterminate', maximum=100)
    progress_bar.start()
    progress_numbers.configure(text="saving")
    wb.save(new_workbook_path)
    print_if_debug("success")
    if not args.keep_barcode_files:
        print_if_debug("removing temp folder " + tempdir)
        shutil.rmtree(tempdir)
        print_if_debug("success")
Exemplo n.º 49
0
def generate_barcode(text):
    writer = ImageWriter()
    options = dict(module_height=9.0, text_distance=0.5, font_size=7, quiet_zone=2.0)
    ean = barcode.get('code39', text, writer=writer)
    dir = 'awb/barcode/'
    return ean.save(MEDIA_ROOT + dir + text, options)
Exemplo n.º 50
0
def _generate_barcode_image(serial_number='1234567890'):
    return barcode.get('ean13', serial_number, writer=ImageWriter()).render()
Exemplo n.º 51
0
def square(barcod):
    ean = barcode.get('ean13',barcod)
    global imgpath
    imgpath = ean.save('image')
Exemplo n.º 52
0
Arquivo: app.py Projeto: h3nj3/PiPos
 def print_barcode(self):
     bar = barcode.get('ean13', self.ean, writer=ImageWriter())
Exemplo n.º 53
0
def barcode_generator(string):
	bcode = barcode.get('code39',string)
	options = dict(compress=False)
	bcode.save('static/'+ bcode.get_fullcode(), options)
	return  bcode.get_fullcode()
Exemplo n.º 54
0
def generate_barcode(outdir, code):
    # 类型列表 ['code39', 'ean', 'ean13', 'ean8', 'gs1', 'gtin', 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca']
    # 生成SVG矢量条形码
    ean = barcode.get('ean13', code)
    with open(outdir + '/' + code + '.svg', 'wb') as f:
        ean.write(f)
Exemplo n.º 55
0
def v_libstockmodify(req,para):# helps to modify the library stock by adding or removing quantity of element whose id is para
    if i_hasPermission(tbl_systemUser.objects.get(username=req.session.get('username')),'library','a'):
        para=int(para)
        uniqueobj=tbl_libItem.objects.get(id=para)
        getitems=uniqueobj.totalquantity.filter(status=True,remove=False)
        
        paymodelist=['Cash','Cheque','Draft']
        errors=[]
        if req.POST.get('modifyLibStock',''):# this will add quantity
            # accessing and validating form elements
            quantity=req.POST.get('quantity','').strip()
            edition=req.POST.get('edition','').strip()
            
            price=req.POST.get('price','').strip()
            suppliername=req.POST.get('suppliername','').strip()
            suppliercontact=req.POST.get('suppliercontact','').strip()
            supplieraddress=req.POST.get('supplieraddress','').strip()
            totalcost=req.POST.get('totalcost','').strip()
            paymentmode=req.POST.get('paymentmode','')
            date=req.POST.get('date','').strip()
            reciptno=req.POST.get('reciptno','').strip()
            donor=req.POST.get('donor','')
            
            try:
                quantity=int(quantity)
            except:
                errors.append("Please enter the valid quantity!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            if not price:
                errors.append("Please enter the price!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            try:
                date1=dateformatConvertor(date)
            except:
                errors.append("Please enter the valid date !")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            if not suppliername:
                errors.append("Please enter the supplier name!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            
            
            if quantity==0:
                errors.append("Quantity cannot be 0!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            if quantity>500:
                errors.append("Please enter the quantity less than 500!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            price=int(price)
            if suppliercontact:
                suppliercontact=int(suppliercontact)
            if totalcost:
                totalcost=int(totalcost)
            
            if donor=="1":
                totalcost=0
                paymentmode=''
                reciptno=''
            #finally adding quantity to database
            
            p3=tbl_itemInfo()
            p3.mrpprice=price
            p3.edition=edition
            
            p3.save()
            
                
            i=0
            while i<quantity:
                p5=tbl_uniqueitemList()
                p5.save()
                ean = barcode.get('ean13','9876'+str(uniqueobj.id)+str(p5.id))
                #filename = ean.save(MEDIA_ROOT+'library/'+str(uniqueobj.id)+'/'+str(i))
                
                #p5.barcodeImage='library/'+str(uniqueobj.id)+'/'+str(i)
                p5.barcodeNo=ean.get_fullcode()
                p5.info=p3
                
                p5.save()
                uniqueobj.totalquantity.add(p5)
                i=i+1
                
                
                
                
                
                
            uniqueobj.save()
            
            
            
            
            # adding supplier information
            p2=tbl_supplier()
            p2.name=suppliername
            p2.address=supplieraddress
            p2.paymentMode=paymentmode
            p2.recipt=reciptno
            p2.quantity=quantity
            if suppliercontact:
                p2.contact=suppliercontact
            if totalcost:
                p2.billamt=totalcost
            p2.date=date1
            p2.info=p3
            p2.save()
            uniqueobj.suppliers.add(p2)
            uniqueobj.save()
            return HttpResponseRedirect('/manageStocks/')
        if req.POST.get('removestock',''):# this will help to deduct the item stock
            remark=req.POST.get('remark','').strip()
            remdate1=req.POST.get('remdate1','').strip()
            getids=""
            try:
                rdate=dateformatConvertor(remdate1)
            except:
                errors.append("Please enter valid date!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            
            
            for data in getitems:
                
                if req.POST.get(str(data.id),''):
                    
                    getids=getids+data.getItemId()+'/'
                    data.remove=True
                    data.save()
            if getids=="":
                errors.append("Please select atleast one item to deduct!")
                return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
            #updating the database
            p1=tbl_removeLibItems()
            p1.ids=getids
            p1.date=rdate
            p1.remark=remark
            p1.save()
            uniqueobj.remove.add(p1)
            uniqueobj.save()
            return HttpResponseRedirect('/manageStocks/')
        return render_to_response('libStockModify.html',locals(),context_instance=RequestContext(req))
Exemplo n.º 56
0
def v_addLibItem(req):# this method helps to purchase new item from supplier
    if i_hasPermission(tbl_systemUser.objects.get(username=req.session.get('username')),'library','a'):
        listitem=['Book','CD-DVD','Magazine','Other']
        paymodelist=['Cash','Draft','Cheque']
        errors=[]
        if req.POST.get('addLibItem',''):# accessing form elements and performing validation on them
            itemname=req.POST.get('itemname','').strip()
            itemcode=req.POST.get('itemcode','').strip()
            itemtype=req.POST.get('itemtype','')
            quantity=req.POST.get('quantity','').strip()
            edition=req.POST.get('edition','').strip()
            author=req.POST.get('author','').strip()
            publication=req.POST.get('publication','').strip()
            price=req.POST.get('price','').strip()
            suppliername=req.POST.get('suppliername','').strip()
            suppliercontact=req.POST.get('suppliercontact','').strip()
            supplieraddress=req.POST.get('supplieraddress','').strip()
            totalcost=req.POST.get('totalcost','').strip()
            paymentmode=req.POST.get('paymentmode','')
            date=req.POST.get('date','').strip()
            reciptno=req.POST.get('reciptno','').strip()
            donor=req.POST.get('donor','')
            if not itemname:
                errors.append("Please enter the item name!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if not itemcode:
                errors.append("Please enter the code!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            try:
                quantity=int(quantity)
            except:
                errors.append("Please enter the valid quantity!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if not price:
                errors.append("Please enter the price!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            try:
                date1=dateformatConvertor(date)
            except:
                errors.append("Please enter the valid date !")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if quantity>500:
                
                errors.append("You can add maximum of 500 items at a time !")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if not suppliername:
                errors.append("Please enter the supplier name!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if tbl_libItem.objects.filter(itemCode=itemcode):
                errors.append("Please enter different code.This code already exist!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            
            if quantity==0:
                errors.append("Quantity cannot be 0!")
                return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            if suppliercontact:
                if len(suppliercontact)<6:
                    errors.append("Please enter valid supplier ContactNo!")
                    return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
            price=int(price)
    
            if suppliercontact:
                suppliercontact=int(suppliercontact)
            if totalcost:
                totalcost=int(totalcost)
            if not os.path.exists(MEDIA_ROOT+'library'):
                os.makedirs(MEDIA_ROOT+'library')
            if donor=="1":
                totalcost=0
                paymentmode=''
                reciptno=''
            #finally saving data to database 
            p1=tbl_libItem()
            p1.itemName=itemname
            p1.itemCode=itemcode
            p1.type=itemtype
            p1.author=author
            p1.publisher=publication
            p1.save()
            if not os.path.exists(MEDIA_ROOT+'library/'+str(p1.id)):
                os.makedirs(MEDIA_ROOT+'library/'+str(p1.id))
            
            x=MEDIA_ROOT+'library/'+str(p1.id)+'/'
            p3=tbl_itemInfo()
            p3.mrpprice=price
            p3.edition=edition
            
            p3.save()
            
            
            p2=tbl_supplier()
            p2.name=suppliername
            p2.address=supplieraddress
            p2.paymentMode=paymentmode
            p2.recipt=reciptno
            p2.quantity=quantity
            if suppliercontact:
                p2.contact=suppliercontact
            if totalcost:
                p2.billamt=totalcost
            p2.date=date1
            p2.info=p3
            p2.save()
            p1.suppliers.add(p2)
            i=1
            while i<=quantity:
                p5=tbl_uniqueitemList()
                p5.save()
                ean = barcode.get('ean13','9876'+str(p1.id)+str(p5.id))
                #filename = ean.save(MEDIA_ROOT+'library/'+str(p1.id)+'/'+str(i))
                
                #p5.barcodeImage='library/'+str(p1.id)+'/'+str(i)
                p5.barcodeNo=ean.get_fullcode()
                p5.info=p3
                
                p5.save()
                p1.totalquantity.add(p5)
                i=i+1
            p1.save()
            return HttpResponseRedirect('/libItems/')
                
        return render_to_response('addLibItem.html',locals(),context_instance=RequestContext(req))
def do_process_workbook():
    print_if_debug("creating temp directory")
    if not args.keep_barcodes_in_home:
        tempdir = tempfile.mkdtemp()
    else:
        temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images')
        os.mkdir(temp_dir_in_cwd)
        tempdir = temp_dir_in_cwd
    print_if_debug("temp directory created as: " + tempdir)
    progress_bar.configure(mode='indeterminate', maximum=100)
    progress_bar.start()
    progress_numbers.configure(text="opening workbook")
    wb = openpyxl.load_workbook(old_workbook_path)
    ws = wb.worksheets[0]
    progress_numbers.configure(text="testing workbook save")
    wb.save(new_workbook_path)
    count = 0
    save_counter = 0
    progress_bar.configure(maximum=ws.max_row, value=count)
    progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
    border_size = int(border_spinbox.get())

    for _ in ws.iter_rows():  # iterate over all rows in current worksheet
        if not process_workbook_keep_alive:
            break
        try:
            count += 1
            progress_bar.configure(maximum=ws.max_row, value=count, mode='determinate')
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
            progress_bar.configure(value=count)
            # get code from column "B", on current row, add a zero to the end to make seven digits
            print_if_debug("getting cell contents on line number " + str(count))
            upc_barcode_number = ws["B" + str(count)].value + "0"
            print_if_debug("cell contents are: " + upc_barcode_number)
            # select barcode type, specify barcode, and select image writer to save as png
            ean = barcode.get('ean8', upc_barcode_number, writer=ImageWriter())
            # select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file.
            # dpi is the conversion from svg image size in mm, to what the image writer thinks is inches.
            ean.default_writer_options['dpi'] = int(dpi_spinbox.get())
            # module height is the barcode bar height in mm
            ean.default_writer_options['module_height'] = float(height_spinbox.get())
            # text distance is the distance between the bottom of the barcode, and the top of the text in mm
            ean.default_writer_options['text_distance'] = 1
            # font size is the text size in pt
            ean.default_writer_options['font_size'] = int(font_size_spinbox.get())
            # quiet zone is the distance from the ends of the barcode to the ends of the image in mm
            ean.default_writer_options['quiet_zone'] = 2
            # save barcode image with generated filename
            print_if_debug("generating barcode image")
            with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file_path:
                filename = ean.save(initial_temp_file_path.name[0:-4])
                print_if_debug("success, barcode image path is: " + filename)
                print_if_debug("opening " + str(filename) + " to add border")
                barcode_image = pil_Image.open(str(filename))  # open image as pil object
                print_if_debug("success")
                print_if_debug("adding barcode and saving")
                img_save = pil_ImageOps.expand(barcode_image, border=border_size,
                                               fill='white')  # add border around image
                width, height = img_save.size  # get image size of barcode with border
                # resize cell to size of image
                ws.column_dimensions['A'].width = int(math.ceil(float(width) * .15))
                ws.row_dimensions[count].height = int(math.ceil(float(height) * .75))
                # write out image to file
                with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path:
                    img_save.save(final_barcode_path.name)
                    print_if_debug("success, final barcode path is: " + final_barcode_path.name)
                    # open image with as openpyxl image object
                    print_if_debug("opening " + final_barcode_path.name + " to insert into output spreadsheet")
                    img = OpenPyXlImage(final_barcode_path.name)
                    print_if_debug("success")
                    # attach image to cell
                    print_if_debug("adding image to cell")
                    img.anchor(ws.cell('A' + str(count)), anchortype='oneCell')
                    # add image to cell
                    ws.add_image(img)
                    save_counter += 1
            print_if_debug("success")
            # This save in the loop frees references to the barcode images,
            #  so that python's garbage collector can clear them
        except Exception as barcode_error:
            print_if_debug(barcode_error)
        if save_counter >= file_limit - 50:
            print_if_debug("saving intermediate workbook to free file handles")
            progress_bar.configure(mode='indeterminate', maximum=100)
            progress_bar.start()
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row) + " saving")
            wb.save(new_workbook_path)
            print_if_debug("success")
            save_counter = 1
            progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
    progress_bar.configure(value=0)
    print_if_debug("saving workbook to file")
    progress_bar.configure(mode='indeterminate', maximum=100)
    progress_bar.start()
    progress_numbers.configure(text="saving")
    wb.save(new_workbook_path)
    print_if_debug("success")
    if not args.keep_barcode_files:
        print_if_debug("removing temp folder " + tempdir)
        shutil.rmtree(tempdir)
        print_if_debug("success")

    progress_bar.stop()
    progress_bar.configure(maximum=100, value=0, mode='determinate')
    progress_numbers.configure(text="")
Exemplo n.º 58
0
import barcode
from barcode.writer import ImageWriter

from generate_ean import getnumber

ean = getnumber()
bar = barcode.get('ean13', ean, writer=ImageWriter())
filename = bar.save('ean13')
Exemplo n.º 59
-3
    def _write_product_table_row(self, work_book, work_sheet, product, line, percent_top):
        writer = ImageWriter()
        writer.set_options({"font_size": 18, "text_distance": 2, "quiet_zone": 2})
        ean = barcode.get("ean13", product.barcode, writer=writer)
        file_name = ean.save("barcode", {"quiet_zone": 2, "text_distance": 2, "module_height": 8})
        size = openpyxl.drawing.Image(file_name).image.size * array([0.35, 0.35])
        img = openpyxl.drawing.Image(file_name, size=size)
        line_number = "A%s" % line
        img.anchor(work_book.worksheets[0].cell(line_number))
        img.drawing.top = percent_top

        work_sheet.append((product.barcode, product.name, product.order, product.quantity))
        row = self._get_last_row(work_sheet)
        row.alignment = self.metadata_style
        work_sheet.append((work_sheet.add_image(img),)),
        return img.drawing.top