예제 #1
0
def getAcc(event=None):
    acc = str(entry1.get())

    BC = barcode.get_barcode_class('gs1_128')  #itf, code39, gs1_128, code128
    BC_img = BC(acc, writer=ImageWriter())
    filename = BC_img.save('barcode',
                           options={
                               "write_text": False,
                               "text": acc + '\n' + acc
                           })

    im = Image.open(r"barcode.png")
    width, height = im.size
    load = im.crop(
        (10, height / 3, width - 10, height))  #Left,Top,Right,Bottom

    #load = Image.open(filename)
    render = ImageTk.PhotoImage(load)
    img = Label(root, image=render)  #, height=40)
    img.image = render
    img.place(x=3, y=50)
예제 #2
0
def create():
    path = e.fileopenbox("请选择要生成条形码的内容", default="*.txt")
    filename = path.split("/")[-1][0:-4]
    isExists = os.path.exists(filename)
    if not isExists:
        os.mkdir(filename)
    else:
        pass
    f = open(path, "r", encoding=getencoding.getencoding(path))
    CODE128 = barcode.get_barcode_class('code128')  # 创建ean13格式的条形码格式对象
    for code in f:
        code2 = code.strip()
        ean = CODE128(code2, writer=ImageWriter())  # 创建条形码对象,内容为5901234123457
        fullname = ean.save(filename + os.sep + code2,
                            options={
                                'module_height': 10.0,
                                "write_text": False
                            })
        # 保存条形码图片,并返回保存路径。图片格式为png
        print(fullname)
    e.msgbox("生成条形码完成")
예제 #3
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
예제 #4
0
def generate_barcode():
  try:
      data = pd.read_csv("ticket.csv")
      bar_list = list(data["ID"])
      # print(bar_list)
  except:
      print("didnt work")
      bar_list = []
  # print(bar_list)
  if not bar_list:
      bar_num = str(random.randint(100000000000,999999999999))
      bar_list.append(bar_num)
  else:
      bar_num = str(random.randint(100000000000,999999999999))
      while bar_num in bar_list:
          bar_num = str(random.randint(100000000000,999999999999))
      bar_list.append(bar_num)
  EAN = barcode.get_barcode_class('ean13')
  ean = EAN(str(bar_num), writer=ImageWriter())
  bar_code = ean.save('ean13_barcode')
  return bar_num, bar_code
예제 #5
0
 def Shop_id(self):
     xjg = ""
     for i in range(0, 10):
         nowTime = datetime.datetime.now().strftime(
             "%Y%m%d%H%M%S")  # 生成当前时间
         randomNum = random.randint(100, 999)  # 生成的随机整数n,其中0<=n<=100
         uniqueNum = str(nowTime) + str(randomNum)
         xjg = uniqueNum
         self.Spgl_sptm.setText(uniqueNum)
         # 获取系统TEMP路径
     self.TEMP_barcode = r"%s\%s" % (environ.get("TMP"), xjg)
     Code = barcode.get_barcode_class('code128')  # 参数为支持的格式
     # 获取条形码对象
     bar = Code(xjg, writer=ImageWriter())
     bar.save(
         self.TEMP_barcode, {
             'module_width': 0.4,
             'module_height': 13.0,
             'font_size': 25,
             'text_distance': 0.5
         })
예제 #6
0
def generagteBarCode(self):
        imagewriter = ImageWriter()
        #保存到图片中
        # add_checksum : Boolean   Add the checksum to code or not (default: True)
        ean = Code39("1234567890", writer=imagewriter, add_checksum=False)
        # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG'
        #print '保存到image2.png'
        ean.save('image2')
        img = Image.open('image2.png')
        #print '展示image2.png'
        img.show()

        # 写入stringio流中
        #i = str(StringIO())
        global i
        ean = Code39("0987654321", writer=imagewriter, add_checksum=False)
        ean.write(i)
        i = StringIO(i.getvalue())
        img1 = Image.open(i)
        #print '保存到stringIO中并以图片方式打开'
        img1.show()
예제 #7
0
def create_barcode(args, parser):
    args.type = args.type.upper()
    if args.type != "SVG" and args.type not in IMG_FORMATS:
        parser.error(
            "Unknown type {type}. Try list action for available types.".format(
                type=args.type))
    args.barcode = args.barcode.lower()
    if args.barcode not in barcode.PROVIDED_BARCODES:
        parser.error(
            "Unknown barcode {bc}. Try list action for available barcodes.".
            format(bc=args.barcode))
    if args.type != "SVG":
        opts = {"format": args.type}
        writer = ImageWriter()
    else:
        opts = {"compress": args.compress}
        writer = SVGWriter()
    out = os.path.normpath(os.path.abspath(args.output))
    name = barcode.generate(args.barcode, args.code, writer, out, opts,
                            args.text)
    print("New barcode saved as {}.".format(name))
예제 #8
0
def get_barcode(
    barcode_text="",
    code="code128",
    margin=6.5,
    height=15.0,
    write_text=True,
    background="white",
    foreground="black",
    font_size=12,
):
    """
    Returns barcode.png for barcode_text
    Usage: <site_url>/api/method/dotted_path_to.get_barcode"""

    buf = BytesIO()
    out = barcode.get(code, barcode_text, writer=ImageWriter()).write(
        buf,
        {
            # barcode options
            # https://python-barcode.readthedocs.io/en/stable/writers/index.html
            # The width of one barcode module in mm as float. Defaults to 0.2.
            "module_width": 0.2,
            # The height of the barcode modules in mm as float. Defaults to 15.0...26.46
            "module_height": flt(height),
            # Distance on the left and on the right from the border to the first (last) barcode module in mm as float. Defaults to 6.5.
            "quiet_zone": flt(margin),
            "font_size": font_size,
            # Do not print text below image
            "write_text": cint(write_text),
            "foreground": foreground,
            "background": background,
            # "text_distance": Distance between the barcode and the text under it in mm as float
        },
    )
    from werkzeug.wrappers import Response

    response = Response()
    response.mimetype = "image/png"
    response.data = buf.getvalue()
    return response
예제 #9
0
 def get_context_data(self, **kwargs):
     barang_obj = Barang.objects.get(id_barang=self.kwargs['pk'])
     EAN = barcode.get_barcode_class('ean8')
     ean = EAN(barang_obj.id_barang, writer=ImageWriter())
     ean.save(os.path.join('static/media/barcodes/' + barang_obj.id_barang))
     barcode_loc = "media/barcodes/" + barang_obj.id_barang + ".png"
     barang_obj.barcode = barcode_loc
     barang_obj.save()
     dict = {
         1: "Januari",
         2: "Februari",
         3: "Maret",
         4: "April",
         5: "Mei",
         6: "Juni",
         7: "Juli",
         8: "Agustus",
         9: "September",
         10: "Oktober",
         11: "November",
         12: "Desember",
     }
     get_day = barang_obj.tgl_pengadaan.day
     get_month = barang_obj.tgl_pengadaan.month
     get_year = barang_obj.tgl_pengadaan.year
     self.kwargs.update({
         'satker':
         barang_obj.id_tempat.id_ruang.id_satker.nama.upper(),
         'nama':
         barang_obj.nama.upper(),
         'id_barang':
         barang_obj.id_barang,
         'tgl_pengadaan':
         str(get_day) + ' ' + dict[get_month].upper() + ' ' + str(get_year),
         'barcode':
         barang_obj.barcode,
     })
     kwargs = self.kwargs
     context = super().get_context_data(**kwargs)
     return context
예제 #10
0
    def set_barcode(self):
        """
            Create barcode file for this customer
        """
        import barcode
        from barcode.writer import ImageWriter
        from cStringIO import StringIO

        db = current.db
        stream = StringIO()

        CODE39 = barcode.get_barcode_class('code39')
        code39_barcode = CODE39(unicode(self.cuID),
                                writer=ImageWriter(),
                                add_checksum=False)
        '''
        Default options (here for future reference);
        
        default_writer_options = {
            'module_width': 0.2,
            'module_height': 15.0,
            'quiet_zone': 6.5,
            'font_size': 10,
            'text_distance': 5.0,
            'background': 'white',
            'foreground': 'black',
            'write_text': True,
            'text': '',
        }
        '''

        code39_barcode.default_writer_options['module_height'] = 5
        code39_barcode.default_writer_options['font_size'] = 7
        code39_barcode.default_writer_options['text_distance'] = 0.5

        code39_barcode.write(stream)
        stream.seek(0)

        self.row.update_record(barcode=db.auth_user.barcode.store(
            stream, filename=unicode(self.cuID) + u'_barcode.png'))
예제 #11
0
async def bq(event):
    """ For .barcode command, genrate a barcode containing the given content. """
    await event.edit("`Sedang memproses...`")
    input_str = event.pattern_match.group(1)
    message = "**Sintaksis** : `.barcode [teks panjang untuk disertakan]`"
    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(
            "**Sintaksis** : `.barcode [teks panjang untuk disertakan]`")

    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()
예제 #12
0
파일: qrcode.py 프로젝트: qkoer/darkuserbot
async def barcode_read(event):
    """ .barcode komutu verilen içeriği içeren bir barkod oluşturur. """
    input_str = extract_args(event)
    message = "Kullanım: `.barcode <eklenecek uzun metin>`"
    reply = await event.get_reply_message()
    if len(input_str) < 1 and not reply:
        await event.edit(message)
        return
    await event.edit("`İşleniyor..`")
    reply_msg_id = event.id
    if reply:
        reply_msg_id = reply.id
        if reply.media:
            downloaded_file_name = await event.client.download_media(reply)
            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 = reply.message
    else:
        message = input_str

    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:
        await event.edit(str(e))
        return
    await event.delete()
예제 #13
0
def test():
    if not os.path.isdir(TESTPATH):
        try:
            os.mkdir(TESTPATH)
        except OSError as e:
            print('Test not run.')
            print('Error:', e)
            sys.exit(1)
    objects = []
    append = lambda x, y: objects.append(OBJECTS.format(filename=x, name=y))
    append_img = lambda x, y: objects.append(IMAGES.format(filename=x, name=y))
    options = dict(module_width=0.495, module_height=25.0)
    for codename, code in TESTCODES:
        bcode = get_barcode(codename, code)
        if codename.startswith('i'):
            options['center_text'] = False
        else:
            options['center_text'] = True
        filename = bcode.save(os.path.join(TESTPATH, codename),
                              options=options)
        print('Code: {0}, Input: {1}, Output: {2}'.format(
            bcode.name, code, bcode.get_fullcode()))
        append(os.path.basename(filename), bcode.name)
        if ImageWriter is not None:
            bcodec = get_barcode_class(codename)
            bcode = bcodec(code, writer=ImageWriter())
            opts = dict(font_size=14, text_distance=1)
            if codename.startswith('i'):
                opts['center_text'] = False
            else:
                opts['center_text'] = True
            filename = bcode.save(os.path.join(TESTPATH, codename),
                                  options=opts)
            append_img(os.path.basename(filename), bcode.name)
        else:
            objects.append(NO_PIL)
    # Save htmlfile with all objects
    with codecs.open(HTMLFILE, 'w', encoding='utf-8') as f:
        obj = '\n'.join(objects)
        f.write(HTML.format(version=version, body=obj))
예제 #14
0
def generate_barcode(receipt, receipt_model):
    """
    generates a barcode for a receipt

    Args:
        receipt(obj): receipt whose barcode is being created for
        receipt_model: model of receipt

    Returns:
        string: url for barcode created
    """
    barcode_number = randint(100000000000, 999999999999)
    image = barcode.get_barcode_class('upca')
    receipt_instance = receipt_model.objects.filter(
        scanned_number=barcode_number)
    if receipt_instance.exists():
        return generate_barcode(receipt, receipt_model)
    barcode_image = image(str(barcode_number), writer=ImageWriter())
    filename = barcode_image.save('receipt')
    image_url = cloudinary.uploader.upload(filename).get('url')
    receipt.scanned_number = barcode_number
    return image_url
예제 #15
0
파일: bot.py 프로젝트: ManuDeBuck/coaster
 def get_item_barcode(self, update, context):
     command_split = update.message.text.split(" ")
     if len(command_split) < 2:
         context.bot.send_message(chat_id=update.effective_chat.id,
                                  text="Format: /get_item_barcode item")
         return
     item_name = command_split[1]
     item = self.items.get_by_item_name(item_name)
     if item is not None:
         filename = "barcodes/{}.png".format(item.barcode)
         if not os.path.isfile(filename):
             code = Code128(item.barcode, writer=ImageWriter())
             code.save("barcodes/{}".format(item.barcode))
         context.bot.send_photo(chat_id=update.effective_chat.id,
                                photo=open(
                                    "barcodes/{}.png".format(item.barcode),
                                    "rb"))
     else:
         context.bot.send_message(
             chat_id=update.effective_chat.id,
             text=f"The item with name {item_name} currently does not exist."
         )
예제 #16
0
    def inv_instructions_button_pressed(self):
        if self.ui.tableView.currentIndex().row() >= 0:
            record = self.model.record(self.ui.tableView.currentIndex().row())
            instruct = record.value('instructions')
            name = record.value('name')

            barcodeNumber = record.value('barcode')

            self.dialog = instructionDialog(name, instruct)
            self.dialog.sendInstruct.connect(self.receive_instruct)

            if len(barcodeNumber) == 13:
                EAN = barcode.get_barcode_class('ean13')
                ean = EAN(barcodeNumber, writer=ImageWriter())

                filename = ean.save('barcode')

                pixmap = QtGui.QPixmap(filename)

                self.dialog.ui.barcodeView.setPixmap(pixmap)

            self.dialog.show()
예제 #17
0
 def save(self, *args, **kwargs):
     # create slug
     maintenance = self.maintenance.replace(' ','')
     self.slug = slugify('{}-Maintenance-{}'.format(self.machine.slug,maintenance))
     # create qr-code
     qrcode_img = qrcode.make(self.slug)
     qrcode_img.save('media/Machines/qrcode/{}.png'.format(self.slug))
     self.qrcode = 'Machines/qrcode/{}.png'.format(self.slug)
     # create barcode
     code128 = barcode.get_barcode_class('code128')
     barcode_img = code128(self.slug, writer=ImageWriter())
     barcode_img.save('media/Machines/barcode/{}'.format(self.slug))
     self.barcode = 'Machines/barcode/{}.png'.format(self.slug)
     # save all
     super().save(*args, **kwargs)
     # create data maintenance
     obj = DataMaintenance.objects.filter(maintenance = self.id)
     if obj.count() == 0:
         DataMaintenance.objects.get_or_create(
             maintenance = Maintenance.objects.get(id=self.id),
             date = timezone.now()
             )
예제 #18
0
    def create(self, vals):
        rec = super(pos_gift_coupon, self).create(vals)
        pos_config_obj = self.env['pos.coupons.setting']
        if pos_config_obj.search_count([('active', '=', True)]) != 1:
            raise Warning(_('Please configure gift coupons'))
        else:
            code = (random.randrange(1111111111111, 9999999999999))

            coupen_barcode = self.env['barcode.nomenclature'].sanitize_ean(
                "%s" % (code))
            rec.write({'c_barcode': coupen_barcode})

            if ImageWriter != None:
                encode = barcode.get('ean13',
                                     coupen_barcode,
                                     writer=ImageWriter())
                filename = encode.save('ean13')
                file = open(filename, 'rb')
                jpgdata = file.read()
                imgdata = base64.encodestring(jpgdata)
                rec.write({'c_barcode_img': imgdata})
                os.remove(filename)

            if pos_config_obj.search_count([('active', '=', True)]) == 1:
                config_record = pos_config_obj.search([('active', '=', True)
                                                       ])[0]
                if config_record.default_availability != -1:
                    if self.search_count(
                        []) == config_record.default_availability:
                        raise Warning(
                            _('You can only create %d coupons  ') %
                            config_record.default_availability)
                config_record = config_record.search([('active', '=', True)
                                                      ])[0]
                if config_record:
                    rec.update({'expiry_date': config_record.max_exp_date})

        return rec
예제 #19
0
파일: qrcode.py 프로젝트: Eko432/RemixBot
async def bq(event):
    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()
예제 #20
0
파일: codebar.py 프로젝트: rechner/Taxidi
def gen(encoding, fileName, text, width=300, height=100):
    """Returns 0 success; all else are errors.
    gen(encoding, fileName, text, width=300, height=100)
    note: geometry settings only valid for code128.
    """

    if encoding not in codes:
        raise NotImplementedError("Unsupported encoding")
        return 2

    if encoding == 'qr':
        #generate QR code
        qr_image = pyqrcode.MakeQRImage(text, br=True)
        fileHandle = file(fileName, 'w')
        qr_image.save(fileHandle, 'PNG')
        fileHandle.close()
        return 0

    elif encoding == 'code128':
        #generate using Code128() by Jostein Leira
        bar = Code128()
        bar.getImage(text, fileName, 300, 100)
        return 0

    else:
        #generate barcode
        pre = barcode.get_barcode(encoding, text, writer=ImageWriter())
        save = pre.save(fileName)

        out = Image.open(save)
        #crop the image
        if encoding == 'code39':
            out = out.crop((28, 10, out.size[0] - 24, 180))
        os.unlink(save)
        fileHandle = file(fileName, 'w')
        out.save(fileHandle, 'PNG')
        fileHandle.close()
        return 0
예제 #21
0
def create_barcode(args, parser):
    args.type = args.type.upper()
    if args.type != 'SVG' and args.type not in IMG_FORMATS:
        parser.error(
            'Unknown type {type}. Try list action for available '
            'types.'.format(type=args.type)
        )
    args.barcode = args.barcode.lower()
    if args.barcode not in barcode.PROVIDED_BARCODES:
        parser.error(
            'Unknown barcode {bc}. Try list action for available '
            'barcodes.'.format(bc=args.barcode)
        )
    if args.type != 'SVG':
        opts = dict(format=args.type)
        writer = ImageWriter()
    else:
        opts = dict(compress=args.compress)
        writer = SVGWriter()
    out = os.path.normpath(os.path.abspath(args.output))
    name = barcode.generate(args.barcode, args.code, writer, out, opts,
                            args.text)
    print('New barcode saved as {0}.'.format(name))
예제 #22
0
def generagteBarCode(x,y):
        imagewriter = ImageWriter()
        #保存到图片中
        # add_checksum : Boolean   Add the checksum to code or not (default: True)
        ean = Code39(x, writer=imagewriter, add_checksum=False)
        # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG'
        print ('保存到image2.png')
        ean.save('./barcode/'+x)
        #draw.text((imgSize[0]*0.6, (imgSize[1]*0.9)), '捷德中国.影音协会', (255,0,0), font=font)
        img = Image.open('./barcode/'+x+'.png')
        print (x+'.png')
        
        
        imgSize=img.size
        font = ImageFont.truetype('simhei.ttf', int((imgSize[0])*0.04))
        #设定字体,和字符大小
        draw = ImageDraw.Draw(img)
        #draw.text(((imgSize[0]-320), (imgSize[1]*0.96)), '捷德中国.影音协会', (255,0,0), font=font)
        draw.text((imgSize[0]*0.05, (imgSize[1]*0.75)), y, (0,0,0), font=font)
        #设定字开始的位置,字的内容,颜色等等
        img.save('./barcode/'+x+'.png', 'PNG')

        img.show()
예제 #23
0
 def generate_barcode_manually(self):
     for record in self.env["product.product"].browse(
             self._context.get("active_id")):
         if self.generate_type == "date":
             bcode = self.env["barcode.nomenclature"].sanitize_ean(
                 "%s%s" %
                 (record.id, datetime.now().strftime("%d%m%y%H%M")))
         else:
             number_random = int("%0.13d" % random.randint(0, 999999999999))
             bcode = self.env["barcode.nomenclature"].sanitize_ean(
                 "%s" % (number_random))
         record.write({"barcode": bcode})
         if ImageWriter is not None:
             ean = BytesIO()
             generate("ean13",
                      u"{}".format(bcode),
                      writer=ImageWriter(),
                      output=ean)
             ean.seek(0)
             jpgdata = ean.read()
             imgdata = base64.encodestring(jpgdata)
             record.write({"barcode_img": imgdata})
     return True
예제 #24
0
async def bq(event):
    """ For .barcode command, genrate a barcode containing the given content. """
    await event.edit("**Processando...**")
    input_str = event.pattern_match.group(1)
    message = "**Sintaxe:** `.barcode <texto longo para incluir>`"
    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 event.edit("**Sintaxe:** `.barcode <texto longo para incluir>`")

    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()
예제 #25
0
def create_barcode(code,product_name,price):
	EAN = barcode.get_barcode_class('code128')
	code_name = code
	ean = EAN(code_name, writer=ImageWriter())
	barcode_image_name = ean.save('{}_{}'.format(code_name,product_name))
	cwd = os.getcwd()
	image = Image.open(barcode_image_name)
	image_main = Image.open('final_img_barcode.jpg')
	main_image_sizex,main_image_sizey = image_main.size
	resized_img = image.resize((main_image_sizex-1500,main_image_sizey-1200))
	image_main.paste(resized_img,(700,500))
	image_main.save("{}/barcodes/{}".format(cwd,barcode_image_name))
	image_after = Image.open("{}/barcodes/{}".format(cwd,barcode_image_name))
	draw = ImageDraw.Draw(image_after)
	font = ImageFont.truetype('roboto-bold.ttf', size=100)
	(x, y) = (main_image_sizex-2300,main_image_sizey-1100) # (1300, 2000)
	message = "RS : {}".format(price)
	color = 'rgb(0, 0, 0)'
	draw.text((x, y), message, fill=color,font=font)
	image_after.save("{}/barcodes/{}".format(cwd,barcode_image_name))
	os.remove(barcode_image_name)
	product_code_ent.delete(0,END)
	product_name_ent.delete(0,END)
	product_price_ent.delete(0,END)
예제 #26
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()
예제 #27
0
    def soft_barcode(self, barcode_type, data, impl='bitImageColumn',
                     module_height=5, module_width=0.2, text_distance=1):

        image_writer = ImageWriter()

        # Check if barcode type exists
        if barcode_type not in barcode.PROVIDED_BARCODES:
            raise BarcodeTypeError(
                'Barcode type {} not supported by software barcode renderer'
                .format(barcode_type))

        # Render the barcode to a fake file
        barcode_class = barcode.get_barcode_class(barcode_type)
        my_code = barcode_class(data, writer=image_writer)

        my_code.write("/dev/null", {
            'module_height': module_height,
            'module_width': module_width,
            'text_distance': text_distance
        })

        # Retrieve the Pillow image and print it
        image = my_code.writer._image
        self.image(image, impl=impl)
예제 #28
0
def generagteBarCode():
    rk = g.enterbox("请输入物品编码:\n", title="条码生成打印")
    barname = rk
    if exist(rk) == True:
        beijian = xlrd.open_workbook(workbook)
        table0 = beijian.sheet_by_name('data')
        nrows = table0.nrows
        for i in range(nrows):
            if table0.row_values(i)[0] == rk:
                i0 = i
                break
        print(i0)
        comments = table0.row_values(i0)[1]
        print(table0.row_values(i0)[1])
    filename = 'image2'
    imagewriter = ImageWriter()

    #保存到图片中
    # add_checksum : Boolean   Add the checksum to code or not (default: True)
    ean = Code39(barname, writer=imagewriter, add_checksum=False)
    # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG'
    #    print ('保存到image2.png')
    ean.save(filename)
    img = Image.open(filename + '.png')
    imgSize = img.size
    font = ImageFont.truetype('simhei.ttf', int((imgSize[0]) * 0.04))
    draw = ImageDraw.Draw(img)
    draw.text((imgSize[0] * 0.05, (imgSize[1] * 0.7)),
              comments, (0, 0, 0),
              font=font)

    #print ('展示image2.png')
    img.show()
    time.sleep(1)
    os.remove(filename + '.png')
    menu()
예제 #29
0
def barcode_to_png(barcode_type, text_str, filename):
    print(type(text_str))
    print("gencode string=" + text_str)

    if text_str == "":
        print("empty")
        return

    imagewriter = ImageWriter()
    # add_checksum : Boolean   Add the checksum to code or not (default: True)

    try:
        if barcode_type == 'Code39':
            bfile = Code39(text_str, writer=imagewriter, add_checksum=False)
        elif barcode_type == 'Code128':
            bfile = Code128(text_str, writer=imagewriter)
        else:
            self.alertmsg.setText("沒有支援該方式!!")
    except Exception as e:
        print(f'An Error occurred: {e}')
        return

    # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG'
    bfile.save(filepath + "\\temp\\image")
예제 #30
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()
예제 #31
-2
 def genera_e_salva(self, codice, nome="Immagine.png", scadenza=None):
     generatore = GeneratoreNomeFile('allegati/')
     zname = generatore(self, nome)
     self.prepara_cartelle(MEDIA_ROOT + zname)
     pngfile = open(MEDIA_ROOT + zname, 'wb')
     writer = ImageWriter()
     writer.dpi = 400
     generate("EAN13", codice, writer=writer, output=pngfile, writer_options={
         "quiet_zone": 0.5,
         "text_distance": 0.5,
         "module_height": 5.5,
         "font_size": 13,
     })
     pngfile.close()
     scadenza = scadenza or domani()
     self.file = zname
     self.nome = nome
     self.scadenza = scadenza
     self.save()
예제 #32
-2
 def calculate_size(self, *args, **kw):
     self.text = ""  # XXX
     if self.custom_module_height:
         self.module_height = self.custom_module_height
     return ImageWriter.calculate_size(self, *args, **kw)
예제 #33
-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