def add_barcode(code, name, bar_width=1): new_barcode = Barcode.objects.create( code = code, name = name, base64_code = base64.b64encode(Code128Encoder(code).get_imagedata(bar_width=bar_width)) ) return new_barcode
def createbar_code128(code): # 1 生成条形码 text = code.upper() encoder = Code128Encoder(text, options={ "ttf_font": "/home/timi06/timi/fonts/simsun.ttf", "ttf_fontsize": 15, "bottom_border": 1, "height": 99, "label_border": 1 }) fs = StringIO() encoder.save(fs) # 参考资料:http://ju.outofmemory.cn/entry/53301,http://firehuman.blog.163.com/blog/static/57331120105260736902/ pngraw = fs.getvalue() fs.close() bs = StringIO() imgo = Image.open(BytesIO(pngraw)) imgo.save(bs, 'jpeg') bss = bs.getvalue() imgbase64 = base64.b64encode(bss) bs.close() return imgbase64
def generateBarcodeImage(self, barcode_type, data, REQUEST=None): # huBarcode's DataMatrix support has limitation for data size. # huBarcode's QRCode support is broken. # more 1-D barcode types can be added by pyBarcode library. barcode_type = barcode_type.lower() if barcode_type == 'datamatrix': from subprocess import Popen, PIPE process = Popen(['dmtxwrite'], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) output, _ = process.communicate(input=data) elif barcode_type == 'ean13': from hubarcode.ean13 import EAN13Encoder encoder = EAN13Encoder(data) output = encoder.get_imagedata() elif barcode_type == 'code128': from hubarcode.code128 import Code128Encoder encoder = Code128Encoder(data) encoder.text = '' # get barcode image only output = encoder.get_imagedata() elif barcode_type == 'qrcode': import qrcode from cStringIO import StringIO fp = StringIO() img = qrcode.make(data) img.save(fp, 'png') fp.seek(0) output = fp.read() else: raise NotImplementedError('barcode_type=%s is not supported' % barcode_type) if REQUEST is not None: REQUEST.RESPONSE.setHeader('Content-Type', 'image/png') return output
def imggen(code): encoder = Code128Encoder(code, options={'bottom_border': 10}) #'width':500 #encoder.save("test.png") dm_in_bytes = io.BytesIO(encoder.get_imagedata()) img = Image.open(dm_in_bytes) return img
def goPartLocalfrom(self): from hubarcode.code128 import Code128Encoder ATTACH_ROOT = share.dINI['ATTACH_ROOT'] tmpath = os.path.join(ATTACH_ROOT, 'tm') code = self.GP('code', '0') or 0 sql_z = """ select coalesce(cstatus,0) cstatus from reddetail where code = '%s' """ % code Lz = self.db.fetch(sql_z) cstatus = Lz.get('cstatus', 0) sql = """ SELECT top 1 h.item_id, h.tm, o.cname, ABS(o.price) price, o.amount, coalesce(mt.txt1,'张') dw, h.pic, case when o.item_id = -10000 then 1 when o.vtype = 233 then 1 else (case when o.edtime < now() then 1 else coalesce(o.cstatus,0) end) end cstatus, o.vtype, case when o.vtype = 231 and o.edays > 0 then to_char(edtime,'YYYY-MM-DD HH24:mm:ss') else to_char(edtime,'YYYY-MM-DD HH24:mm:ss') end edtime, CASE WHEN o.vtype = 233 and coalesce(o.cstatus,0) = 1 THEN '(已充值)' WHEN o.vtype = 233 and coalesce(o.cstatus,0) = 0 THEN '(充值中)' WHEN o.vtype = 232 and coalesce(o.cstatus,0) = 0 and o.edtime < now() THEN '(已过期)' WHEN o.vtype = 232 and coalesce(o.cstatus,0) = 0 and o.edtime > now() THEN '(未领取)' WHEN o.vtype = 232 and coalesce(o.cstatus,0) = 1 THEN '(已领取)' WHEN o.vtype = 231 AND coalesce(o.cstatus,0) = 1 THEN '(已使用)' WHEN o.vtype = 231 AND coalesce(o.cstatus,0) = 0 AND o.edtime < now() THEN '(已过期)' WHEN o.vtype = 231 AND coalesce(o.cstatus,0) = 0 AND o.edtime > now() THEN '(未使用)' ELSE '(无效)' END icstatus from v_reddetail o left join hd_item_info h(nolock) on h.item_id=o.item_id LEFT JOIN mtc_t AS mt ON mt.[type] = 'DW' AND mt.id = h.unit where o.code='%s' and o.cid = %s """ % (code, self.usr_id) L = self.db.fetch(sql) self.assign('code', code) self.assign('cstatus', cstatus) self.assign('item', L) encoder = Code128Encoder(code, options={ "ttf_font": "C:/Windows/Fonts/SimHei.ttf", "ttf_fontsize": 13, "bottom_border": 0, "height": 90, "label_border": 3 }) mytm = os.path.join(tmpath, "%s.png" % code) encoder.save(mytm, bar_width=2) #判断订单是否可以自主取消 order_status = self.get_order_status(code) return self.display('H001_local.html')
def print_id(self, param, pos): self.progress.start() if not self.user['id_card']: self.set_id("fd_" + self.user['name']) enc = Code128Encoder(self.user['id_card']) enc.height = 300 png = enc.get_imagedata() p = subprocess.Popen(['lp', '-d', 'labeldrucker', '-'], stdin=subprocess.PIPE) p.communicate(input=png) time.sleep(10)
def si_pay_print(request, si_pay_id): si_pay = model_filter(request, SI_Pay.objects.all()).get(id=si_pay_id) if si_pay.pay_stat not in ['verify', 'close']: return render(request, "echo.html", {'message': u'报账单的状态是已验证的才允许执行该操作!'}) tempfile = TempFile() img = Code128Encoder(si_pay.pay_no, options={'ttf_font': os.path.join(BASE_DIR, 'X', 'static', 'lib', 'FreeMonoBold.ttf') , 'ttf_fontsize': 26, "bottom_border": 12, 'height': 120, 'label_border': 0} ).save(tempfile.path, bar_width=2) base64_img = base64.b64encode(tempfile.read_and_close()) tempfile.close() return render(request, "si_pay_print.html", {'pay_name': si_pay, 'base64_img': base64_img})
def my_handler(sender, **kwargs): #raise IOError(kwargs) instance = kwargs.get('instance') # raise IOError(instance) if instance.barcode_EAN13: encoder = EAN13Encoder(instance.barcode_EAN13) encoder.save(MEDIA_ROOT + '/barcodes/' + 'ean13-' + str(instance.id) + '.png') b = MyBarcode(product=instance, barcode='/barcodes/' + 'ean13-' + str(instance.id) + '.png') b.save() if instance.barcode_EAN128: encoder = Code128Encoder(instance.barcode_EAN128) encoder.save(MEDIA_ROOT + '/barcodes/' + 'ean128-' + str(instance.id) + '.png') b = MyBarcode(product=instance, barcode='/barcodes/' + 'ean128-' + str(instance.id) + '.png') b.save()
def generate(codec, text, bar_width=3, options=code128_default_options): ''' 生成条码 codec: 'ean13', 'code128'等 text: 文本串 bar_width: options: 返回一个wx.Bitmap ''' n = codec.upper() if n == 'CODE128': enc = Code128Encoder(text, options=options) # (176, 528) to (57, 405) elif n== 'EAN13': enc = EAN13Encoder(text) # (169, 339) to (65, 185) else: raise ValueError('%s not yet supported' % codec) pilimage = resize(enc.get_pilimage(bar_width), codec) return PilImageToWxBitmap(pilimage)
def save_barcode(date, file_name, text): rm = {} try: encoder = Code128Encoder(text, options={ "ttf_fontsize": 12, "bottom_border": 15, "height": 50, "label_border": 2 }) date_list = date.split("-") year = date_list[0] month = date_list[1] day = date_list[2] make_dir_year = SSH_MEDIA_SERVER.get( 'LOCAL_MEDIA_BASE') + file_name + "/" + year make_dir_month = SSH_MEDIA_SERVER.get( 'LOCAL_MEDIA_BASE') + file_name + "/" + year + "/" + month make_dir_day = SSH_MEDIA_SERVER.get( 'LOCAL_MEDIA_BASE' ) + file_name + "/" + year + "/" + month + "/" + day if not os.path.exists(make_dir_year): os.makedirs(make_dir_day) if not os.path.exists(make_dir_month): os.makedirs(make_dir_day) if not os.path.exists(make_dir_day): os.makedirs(make_dir_day) img_src = make_dir_day + "/" + text + ".png" encoder.save(img_src, bar_width=1) new_img_src = "media/" + file_name + "/" + year + "/" + month + "/" + day + "/" + text + ".png" rm['code'] = 0 rm['data'] = new_img_src return rm except Exception as e: logging.debug('save_barcode Exception: %s' % str(e)) rm['code'] = -1 rm['data'] = '' return rm
def imprimir_etiquetas_cajas(pallobj, articuloobj, usuario): ETIQUETA_DIR = '%s/label_files_cajas' % PROJECT_ROOT ahora = datetime.datetime.now() pdf=FPDF('L','cm',(10, 12.5)) pdf.add_page() pdf.set_font('Arial',style='',size=6) pdf.set_y(1) pdf.set_x(0.6) pdf.cell(1, 0, 'ARTICULO: %s - %s' % (articuloobj.articulocod, articuloobj.articulo_descripcion), align='L') pdf.set_y(1.5) pdf.set_x(0.6) pdf.cell(1, 0, 'LOTE: %s UNIDADES: %s' % (pallobj.articulo_lote, pallobj.articulo_unidades_x_pall), align='L') pdf.set_y(1.8) pdf.set_x(0.6) #linea pdf.line(0.5, 2, 11.5, 2) #seccion producto barra_articulo = Code128Encoder('%s|%s' % (articuloobj.codigo_barra_caja, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), options={'height':60, 'label_border': 1, 'bottom_border': 5}) barra_articulo.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), bar_width=1) pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), x=0.8, y=2.1) pdf.line(0.5, 4.5, 11.5, 4.5) pdf.set_y(4.7) pdf.set_x(0.5) pdf.cell(1, 0, 'BODEGA: %s HORA: %s FECHA: %s IMPRESO POR: %s' % (pallobj.bodega, ahora.strftime('%H:%M:%S'), ahora.strftime('%d/%m/%Y'), usuario), align='L') pdf.output('%s/%s_%s.pdf' % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d'))) pdf.close() cups_server = CupsServer(settings.CUPS_ADMIN[0], settings.CUPS_ADMIN[1] ) cups_server.modo_admin() for a in range(4): cups_server.imprimir_trabajo('Zebra_TLP2844', "%s/%s_%s.jpg" % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), {})
from hubarcode.code128 import Code128Encoder from PIL import Image, ImageDraw, ImageFont #logging.getLogger("code128").setLevel(logging.DEBUG) #logging.getLogger("code128").addHandler(logging.StreamHandler(sys.stdout)) #12-80 10-80 10-60 12-60 10-70 12-70 10-70 ''' 使用huBarcode,pygame和PIL生成条形码 ''' if __name__ == "__main__": #1 生成条形码 text = "068080835AD000D10701014111".upper() encoder = Code128Encoder(text, options={ "ttf_font": "C:/Windows/Fonts/SimHei.ttf", "ttf_fontsize": 12, "bottom_border": 15, "height": 70, "label_border": 2 }) encoder.save("test.png", bar_width=1) #2 生成条码描述 pygame.init() content = u"P07D111140 T07D1111407010 20150321113322" font = pygame.font.SysFont('SimHei', 10) ftext = font.render(content, True, (0, 0, 0)) pygame.image.save(ftext, "t.png") #3 合成中文文字到条形码,生成新的条码 img = Image.open("test.png") img_w, img_h = img.size
def generate_barcode(self, euro, barcode): enc = Code128Encoder(barcode) enc.height = 300 png = enc.get_imagedata() return Image.open(StringIO(png))
"""Example code for code128 library""" __revision__ = "$Revision: 1$" from hubarcode.code128 import Code128Encoder import logging, sys logging.getLogger("code128").setLevel(logging.DEBUG) logging.getLogger("code128").addHandler(logging.StreamHandler(sys.stdout)) if __name__ == "__main__": encoder = Code128Encoder(sys.argv[1]) encoder.save("test.png")
def imprimir_etiquetas(palletsobjs, usuario, reimpresion): ETIQUETA_DIR = '%s/label_files' % PROJECT_ROOT ahora = datetime.datetime.now() for pallobj in palletsobjs: pdf=FPDF('P','cm',(10, 12.5)) pdf.add_page() pdf.set_font('Arial',style='',size=55) pdf.set_y(1) pdf.set_x(0.6) if pallobj.pallet_completo_010: pdf.cell(1, 0, '%s-C' % pallobj.pall_numero, align='L') else: pdf.cell(1, 0, '%s-I' % pallobj.pall_numero, align='L') # pdf.cell(1, 0, '%s' % '23423554', align='L') pdf.set_font('Arial',style='',size=5) pdf.set_y(2.2) pdf.set_x(8.5) pdf.cell(1, 0, '%s' % ahora.strftime('%d/%m/%Y'), align='R') pdf.set_y(2.4) pdf.set_x(8.5) pdf.cell(1,0, '%s' % ahora.strftime('%H:%M:%S'), align='R') pdf.set_y(2.6) pdf.set_x(8.5) pdf.cell(1,0, usuario, align='R') pdf.set_font('Arial',style='',size=8) pdf.set_y(2.2) pdf.set_x(0.6) pdf.cell(1,0, 'PROFORMA: ', align='L') pdf.set_x(2.8) pdf.cell(1,0, pallobj.pall_proforma, align='L') pdf.set_y(2.6) pdf.set_x(0.6) pdf.cell(1,0, 'LOTE: ', align='L') pdf.set_x(2.8) pdf.cell(1,0, pallobj.articulo_lote, align='L') #vencimiento pdf.set_y(3) pdf.set_x(0.6) pdf.cell(1,0, 'VENCIMIENTO: ', align='L') pdf.set_x(2.8) pdf.cell(1,0, pallobj.articulo_fecha_vencimiento.strftime('%d/%m/%Y'), align='L') #cajas pdf.set_y(3.4) pdf.set_x(0.6) pdf.cell(1,0, 'CAJAS: ', align='L') pdf.set_x(2.8) pdf.cell(1,0, str(pallobj.pall_articulo_cajas), align='L') #unidades pdf.set_x(3.5) pdf.cell(1,0, 'UNIDADES:', align='L') pdf.set_x(5.2) pdf.cell(1,0, str(pallobj.pall_articulo_unidades), align='L') #totales pdf.set_x(5.6) pdf.cell(1,0, 'TOTAL:', align='L') pdf.set_x(6.7) pdf.cell(1,0, str(pallobj.get_pall_cantidad()), align='L') #averiados pdf.set_y(3.8) pdf.set_x(0.6) pdf.cell(1,0, 'AVERIADOS: ', align='L') pdf.set_x(2.8) pdf.cell(1,0, str(pallobj.pall_averiados_cantidad_cajas), align='L') #averiados unidades pdf.set_x(3.5) pdf.cell(1,0, 'UNIDADES:', align='L') pdf.set_x(5.2) pdf.cell(1,0, str(pallobj.pall_averiados_cantidad_sueltas), align='L') #totales averiados pdf.set_x(5.6) pdf.cell(1,0, 'TOTAL:', align='L') pdf.set_x(6.7) pdf.cell(1,0, str(pallobj.get_pall_cantidad_averiados()), align='L') #linea pdf.line(0.5, 4, 9.5, 4) #seccion producto barra_articulo = Code128Encoder(str(pallobj.articulo_cod),options={'height':60, 'label_border': 1, 'bottom_border': 5}) barra_articulo.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), bar_width=1) pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), x=0.5, y=4.1) #linea vertical, separa codigo barra articulo de la descripcion del articulo pdf.line(3.1, 4, 3.1, 6.5) #descripcion del articulo pdf.set_y(4.3) pdf.set_x(3.2) pdf.cell(1,0, 'ARTICULO:', align='L') pdf.set_x(4.8) pdf.cell(1,0, str(pallobj.articulo_cod), align='L') pdf.set_font('Arial',style='',size=10) pdf.set_y(4.5) pdf.set_x(3.2) pdf.multi_cell(6.5,0.5, pallobj.articulo_descripcion, align='L') #linea de cierre pdf.line(0.5, 6.5, 9.5, 6.5) pdf.set_font('Arial',style='',size=8) #vencimiento barra_vencimiento = Code128Encoder(str(pallobj.articulo_fecha_vencimiento.strftime('%d/%m/%Y')),options={'height':40, 'label_border': 1, 'bottom_border': 5}) barra_vencimiento.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_fecha_vencimiento.strftime('%d%m%Y')), bar_width=1) pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_fecha_vencimiento.strftime('%d%m%Y')), x=0.5, y=6.6, type='png') pdf.set_y(6.9) pdf.set_x(5.6) pdf.cell(1,0, 'VENCIMIENTO', align='L') #ultima linea de cierre pdf.line(0.5, 8.2, 9.5, 8.2) #pallet barra_pallet = Code128Encoder(str(pallobj.pall_numero),options={'height':65, 'label_border': 1, 'bottom_border': 5, 'show_label': False}) barra_pallet.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.pall_numero), bar_width=1) pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.pall_numero), x=0, y=8.3, type='png', w=10, h=4) cups_server = CupsServer(settings.CUPS_ADMIN[0], settings.CUPS_ADMIN[1] ) cups_server.modo_admin() pdf.set_font('Arial',style='',size=7) for ib in range(4): a = ib + 1 pdf_temp = copy.deepcopy(pdf) pdf_temp.set_y(2.9) pdf_temp.set_x(8.5) if reimpresion: labelinte = 'COPIA %s/4' % a pdf_temp.cell(1,0, labelinte, align='R') else: labelinte = 'ORIGINAL %s/4' % a pdf_temp.cell(1,0, labelinte, align='R') if not pallobj.pallet_completo_010: pdf_temp.set_y(3.2) pdf_temp.set_x(8.5) pdf_temp.cell(1,0, 'INCOMPLETO', align='R') pdf_temp.output('%s/%s_%s.pdf' % (ETIQUETA_DIR, pallobj.pall_numero, a)) with Image(filename="%s/%s_%s.pdf" % (ETIQUETA_DIR, pallobj.pall_numero, a), resolution=(250,250)) as img: img.save(filename="%s/%s_%s.jpg" % (ETIQUETA_DIR, pallobj.pall_numero, a)) cups_server.imprimir_trabajo('Zebra_TLP2844', "%s/%s_%s.jpg" % (ETIQUETA_DIR, pallobj.pall_numero, a), {}) pdf.close() if reimpresion: pallobj.reimpresion_etiquetado_010=True pallobj.reimpresion_etiquetado_010_por = usuario pallobj.reimpresion_etiquetado_010_fecha = ahora pallobj.reimpresion_etiquetado_010_hora = ahora pallobj.save() pallobj.etiquetado_09=True pallobj.etiquetado_09_por = usuario pallobj.etiquetado_09_fecha = ahora pallobj.etiquetado_09_hora = ahora pallobj.save()