def gen_bar_code(request, code): """Generate a bar code""" fp = StringIO() wr = barcode.writer.ImageWriter() wr.format = 'JPEG' barcode.generate('isbn' if isbnlib.is_isbn13(code) else 'code39', str(code), writer=wr, output=fp, writer_options={'write_text': False, 'module_width': 0.1, 'module_height': 2.0, 'quiet_zone': 0.0}) return HttpResponse(fp.getvalue(), content_type="image/png")
def gen_ean13(content): try: int(content) except ValueError: return None fp = StringIO() notext = barcode.writer.ImageWriter() barcode.generate("EAN13", str(content), output=fp, writer=notext) image = fp.getvalue() fp.close() return image
def get(self, *args, **kwargs): fp = StringIO() code39 = barcode.generate('Code39', '123456789012', writer=barcode.writer.ImageWriter(), output=fp) # filename = code39.save('img') response = HttpResponse(code39, content_type='application/png') response['Content-Disposition'] = 'filename="img.png"' return response
def make_barcode(save_path=QRCODE_PICTURE_PATH, barcode_length=8): """ 生成条形码 返回:条形码数字及条形码文件名 """ source_data = make_random_number_of_string(barcode_length) generate_dict = { 8: { 'name': 'EAN8', 'width': 0.96 }, 13: { 'name': 'EAN13', 'width': 0.66 } } fname = '%s.png' % make_random_char_and_number_of_string(20) fname_path = os.path.join(save_path, fname) if not os.path.isdir(save_path): os.makedirs(save_path) fp = open(fname_path, 'wb') writer = ImageWriter() generate_name = generate_dict[barcode_length]['name'] width = generate_dict[barcode_length]['width'] generate(generate_name, source_data, writer=writer, output=fp, writer_options={ 'module_width': width, 'module_height': 30 }) fp.close() return writer.text, fname_path
def gen_code39(content): fp = StringIO() makepng = barcode.writer.ImageWriter() barcode.generate("Code39", content, output=fp, writer=makepng) image = fp.getvalue() fp.close() return image
def write_images(filtered_codes, doc): from io import BytesIO import barcode from barcode.writer import ImageWriter import base64 from barcode import generate # module_width: The width of one barcode module in mm as float. Defaults to 0.2. # module_height: The height of the barcode modules in mm as float. Defaults to 15.0. # quiet_zone: 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. # font_path: Path to the font file to be used. Defaults to DejaVuSansMono (which is bundled with this package). # font_size: Font size of the text under the barcode in pt as integer. Defaults to 10. # text_distance: Distance between the barcode and the text under it in mm as float. Defaults to 5.0. # background: The background color of the created barcode as string. Defaults to white. # foreground: The foreground and text color of the created barcode as string. Defaults to black. CODE128 = barcode.get_barcode_class('code128') images = [] for sno in filtered_codes: # print to a file-like object: rv = BytesIO() writerx=ImageWriter() writer_options = {"module_width": doc.module_width, "module_height": doc.module_height, "font_size": doc.font_size , "text_distance": doc.text_distance, "quiet_zone": doc.quiet_zone} generate('code128', str(sno), writer=writerx, output=rv, writer_options=writer_options,text=None) img_str = base64.b64encode(rv.getvalue()).decode() images.append(img_str) rv.close() return images
def test_generate_with_file_and_writer(): with open(os.path.join(TESTPATH, "generate_with_file_and_writer.jpeg"), "wb") as f: barcode.generate("ean13", "123455559121112", output=f, writer=SVGWriter())
def generate_barcode(self): for record in self.env["product.product"].browse( self._context.get("active_ids")): if not self.overwrite and record.barcode: continue 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)) ean = BytesIO() generate("ean13", u"{}".format(bcode), writer=ImageWriter(), output=ean) ean.seek(0) jpgdata = ean.read() imgdata = base64.encodestring(jpgdata) record.write({"barcode": bcode, "barcode_img": imgdata}) return True
def get_barcode_128(self): if self.claveacceso: file_data = StringIO.StringIO() generate('code128', u'{}'.format(self.claveacceso), writer=ImageWriter(), output=file_data) file_data.seek(0) self.barcode128 = base64.encodestring(file_data.read())
def medical_barcode(id): path = r'C:\Users\tomsk\Desktop\SM\small_clinic_study\static\images\barcode_med' digit = random.randint(11, 10**11) if len(str(id)) == 1: code = str(digit) + '0' + str(id) generate('EAN13', code, output=path) else: code = str(digit) + str(id) generate('EAN13', code, output=path)
def ean_svg(texto): if not texto: return '' arq = BytesIO() barcode.generate('EAN', texto, output=arq, writer_options={'write_text': False}) return arq.getvalue()
def barcode(event, context): buf = BytesIO() generate('EAN13', '5901234123457', writer=SVGWriter(), output=buf) result = buf.getvalue().decode('utf-8') return { 'statusCode': 200, 'headers': { 'Content-Type': 'image/svg+xml', }, 'body': result, 'isBase64Encoded': False, }
def code128_svg(texto): if not texto: return '' texto = tira_acentos_ascii(texto) arq = BytesIO() barcode.generate('Code128', texto, output=arq, writer_options={'write_text': False}) return arq.getvalue()
def mail_label_maker(doctor, barcode_num, command_type, order_num): """ Create a pdf mail label for the corresponding command number :param doctor: Dictionary :param barcode_num: Int :param command_type: Str :param order_num: Str :return: - """ doc = dict( list(doctor['l'].items()) + list(doctor['g'].items()) + list(doctor['h'].items())) doc['g_order_number'] = order_num doc['g_target_name'] = command_type doc['l_bar_code'] = barcode_num if len(barcode_num) == 24: generate('code128', barcode_num, output='barcode') with open("barcode.svg", mode='r') as f: svg_barcode = ''.join(f.readlines()[5:]) top = '<svg x="121px" y="81px" height="10.000mm" width="40.000mm" xmlns="http://www.w3.org/2000/svg">' doc['image_bar_code'] = top + svg_barcode os.remove('barcode.svg') with open("templates/mail_labels.svg", mode='r') as f: template = Template(f.read()) filled_template = template.substitute(doc) with open("tmp_label.svg", mode='w+') as f: f.write(filled_template) if command_type in notebooks: path = 'mail_labels/notebooks/' else: path = 'mail_labels/memos/' file_path = path + order_num tmp = file_path i = 0 while os.path.exists(tmp + '.pdf'): tmp = file_path + '_' + str(i) i += 1 cairosvg.svg2pdf(url="tmp_label.svg", write_to=tmp + '.pdf') os.remove("tmp_label.svg") else: print( "An error occurred, we can't provide this mail label because the given code doesn't fit the requirements" "\nDenied barcode:" + barcode_num + '\n With order number' + order_num + '\n\n')
def sendEmail(self, email, ticketNum, blurb, imageName): if not mail.is_email_valid(email): self.response.write("<html><body>hello</body></html>") #prompt user to enter a valid address else: message = mail.EmailMessage(sender="John Cleese <*****@*****.**>", subject="Your Asha for Education ticket purchase was successful!") message.to = email message.body = """ Hello, Your request for a ticket with Asha for Education has been approved. Please print the attached ticket and bring it with you to the event. Thank you. Asha for Education """ # Generate image string x = barcode.generate(ticketNum, blurb, imageName) output = StringIO.StringIO() x.save(output, "PNG") message.attachments = [('ticket.png', output.getvalue())] output.close() message.send()
def barcode_generator(request, uid): if request.POST: uid = request.POST.get('uuid') if uid: try: child = Child_detail.objects.get(unique_id_no=uid) img = child.photograph img_name = str(img).replace(".jpg", ".125x125.jpg") student_barcode = generate('EAN13', uid, output='%s/%s' % (settings.MEDIA_ROOT, uid)) return render( request, 'students/id_card/id_card.html', { 'child': child, 'student_barcode': student_barcode, 'img_name': img_name }) except: return render(request, 'students/id_card/id_card.html', {'error': "Invalid UID. Please try again"}) else: return render(request, 'students/id_card/id_card.html')
def generateBarCode_simple(type, data, rotate=0): fp = BytesIO() writer_options = { 'module_width': 0.08, 'module_height': 1.4, 'quiet_zone': 0.1, 'font_size': 5, 'text_distance': 0.7, } barcode.generate(type, str(data), writer=ImageWriter(), output=fp, writer_options=writer_options) return PILImage.open(fp)
def __init__(self, code, type='code128'): self.barcode = io.BytesIO() self.EAN = BCLibrary.generate(type, str(code), writer=ImageWriter(), output=self.barcode) self.barcode = Image.open(self.barcode).convert("RGBA") self.width, self.height = self.barcode.size
def generate_barcode(self, code, codeformat): cachedir = self.cachepath() cachedpath = "%s/%s" % (cachedir, code) cachedpathwithext = "%s.%s" % (cachedpath, self.cachedext()) cherrypy.log("generate_barcode(%s) to %s" % (code, cachedpath)) if (not os.path.isfile(cachedpathwithext)): cachedfullname = generate(codeformat, code, output=cachedpath) return '%s/%s.%s' % (self.cacheuri(), code, self.cachedext())
def test_generate_with_filepath(): # FIXME: extension is added to the filepath even if you include it. rv = barcode.generate( "ean13", "123455559121112", output=os.path.join(TESTPATH, "generate_with_filepath"), ) assert rv == os.path.abspath( os.path.join(TESTPATH, "generate_with_filepath.svg"))
def mail_label_maker(doctor, num, command_type, labels): """ Create a pdf mail label for the corresponding command number :param doctor: Dictionary :param num: Int :param command_type: Str :param labels: Dictionary :return: - """ doc = dict(list(doctor['l'].items()) + list(doctor['g'].items()) + list(doctor['h'].items())) if '.' in doctor['h']['h_inami_number']: inami_number = int(doctor['h']['h_inami_number'].replace('.', '')) else: inami_number = int(''.join([str(ord(e)) for e in doc['h_last_name'] + doc['h_first_name']])) doc['g_order_number'] = labels[inami_number][num][3] doc['g_target_name'] = command_type doc['l_bar_code'] = num if len(num) == 24: generate('code128', num, output='barcode') with open("barcode.svg", mode='r') as f: svg_barcode = ''.join(f.readlines()[5:]) top = '<svg x="121px" y="81px" height="10.000mm" width="40.000mm" xmlns="http://www.w3.org/2000/svg">' doc['image_bar_code'] = top + svg_barcode os.remove('barcode.svg') with open("templates/mail_labels.svg", mode='r') as f: template = Template(f.read()) filled_template = template.substitute(doc) with open(str(num) + ".svg", mode='w+') as f: f.write(filled_template) if command_type in notebooks: path = 'mail_labels/notebooks/' else: path = 'mail_labels/memos/' cairosvg.svg2pdf(url=str(num) + '.svg', write_to=path + str(num) + '.pdf') labels[inami_number][num] += (path + str(num) + '.pdf',) os.remove(str(num) + '.svg') else: print("An error occurred, we can't provide this mail label because the given code doesn't fit the requirements" "\nDenied order number:" + num + '\n With code' + code + '\n\n')
def gen_bar_code(request, code): """Generate a bar code""" fp = StringIO() wr = barcode.writer.ImageWriter() wr.format = 'JPEG' barcode.generate('isbn' if isbnlib.is_isbn13(code) else 'code39', str(code), writer=wr, output=fp, writer_options={ 'write_text': False, 'module_width': 0.1, 'module_height': 2.0, 'quiet_zone': 0.0 }) return HttpResponse(fp.getvalue(), content_type="image/png")
def generate_barcode(self): '''EAN = barcode.get_barcode('code39') ean = EAN(u'serials') fullname = ean.save('code39_barcode')''' barcode = generate('code39', self.serials, writer=ImageWriter(), output='static/images/barcode_png') barcode_URL = "static/images/barcode_png.png" return barcode_URL
def render(self): d = self.data writer = BarcodeWriter(self.data.draw_label) self.render_error = None try: img = barcode.generate(d.code_type, d.text, writer, pil=True) except Exception as x: self.render_error = x return QImage(0, 0, QImage.Format_ARGB32) return img
def create(): # check if the post request has the file part if 'images[]' not in request.files: return json_response({'error': 'file did not upload correctly'}, 422) images = request.files.getlist('images[]') barcode_counter = 0 for image in images: #Save to temp tmp_filename = '/tmp/' + random_string() + '.png' file = image file.save(tmp_filename) #Analyze bd = BarcodeDecoder(tmp_filename) barcode_value, barcode_type = bd.extract() #If a value is extracted if barcode_value: #Save to db data = {} data['value'] = barcode_value data['upload_time'] = str(datetime.datetime.now()) barcode = BarcodeSchema().load(json.loads(json.dumps(data))) if hasattr(barcode, 'errors'): return json_response({'error': barcode.errors}, 422) barcode = Barcode().create_barcode_for(barcode) #Move to folder named after ID directory = app.config['BARCODE_DIRECTORY'] + barcode['_id'] os.makedirs(directory) filename = secure_filename('source.png') os.rename(tmp_filename, os.path.join(directory, filename)) #Generate barcode image image_name = barcode_builder.generate( barcode_type, barcode_value, output=directory + '/result', writer=barcode_builder.writer.ImageWriter()) barcode_counter += 1 else: os.remove(tmp_filename) return json_response({ 'images_sent': len(images), 'barcodes_found': barcode_counter, 'barcodes': Barcode().find_all_barcodes() })
def render_barcode(request, doc_id): item = WFItem.get(doc_id) if not item or item.inventory_nbr is None or barcode is None: return HttpResponseNotFound() if ImageWriter is not None: writer = ImageWriter() mimetype = "image/png" else: # PIL not available, use SVG output instead writer = None mimetype = "image/svg+xml" output = StringIO() barcode.generate("code39", item.inventory_nbr, writer, output, { 'module_width': 0.4, 'module_height': 12, 'text_distance': 3, 'text_size': 12, 'dpi': 96, }) return HttpResponse(output.getvalue(), mimetype=mimetype)
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()
def render_barcode(request, doc_id): item = WFItem.get(doc_id) if not item or item.inventory_nbr is None or barcode is None: return HttpResponseNotFound() if ImageWriter is not None: writer = ImageWriter() mimetype = "image/png" else: # PIL not available, use SVG output instead writer = None mimetype = "image/svg+xml" output = StringIO() barcode.generate( "code39", item.inventory_nbr, writer, output, { 'module_width': 0.4, 'module_height': 12, 'text_distance': 3, 'text_size': 12, 'dpi': 96, }) return HttpResponse(output.getvalue(), mimetype=mimetype)
def mkbar_svg_h(self): try: type_of_bar = self.ui.barcombo.currentText() payload = self.ui.payload.text() where_to_save = getNameForFile() noBarText = not self.ui.noBarText.isChecked() if self.ui.rad_name.isChecked(): where_to_save = self.ui.fname.text() name = generate(type_of_bar, payload, output='results bars/' + where_to_save, writer_options={'write_text': noBarText}) except Exception as e: self.mbox(str(e))
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) print('New barcode saved as {0}.'.format(name))
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))
def save(self, path, writer_options=None): """ Save barcode in SVG format. :param path: path to SVG file with or without ".svg" extension :param writer_options: Common options from pyBarcode \ http://pythonhosted.org/pyBarcode/writers/index.html?#common-options :return: a string with the name of the file generated """ path = self._strip_dotsvg(path) if writer_options is None: writer_options = self.defaults.copy() else: for k, v in self.defaults.items(): writer_options.setdefault(k, v) return generate('code128', self.code(), output=path, writer_options=writer_options)
def save(self, path, writer_options=None): """ Save barcode in SVG format. :param path: path to SVG file with or without ".svg" extension :param writer_options: Common options from pyBarcode \ http://pythonhosted.org/pyBarcode/writers/index.html?#common-options :return: a string with the name of the file generated """ path = self._strip_dotsvg(path) if writer_options is None: writer_options = self.defaults.copy() else: for k, v in self.defaults.items(): writer_options.setdefault(k, v) return generate( 'code128', self.code(), output=path, writer_options=writer_options )
def post(self, request): form = AddSampleForm(request.POST, request.FILES) if form.is_valid(): print(form.cleaned_data) number_of_samples_that_day = Sample.objects.filter(date_received=form.cleaned_data['date_received']).count() sample_code = '{}-{}'.format(form.cleaned_data['date_received'],number_of_samples_that_day+1) data = form.cleaned_data data['sample_code'] = sample_code data['user'] = request.user data['user_id'] = request.user.pk filename = f'inventory/static/img/{sample_code}' database_filename = f'img/{sample_code}.svg' barcode = generate('code128', sample_code, output=filename) data['barcode'] = database_filename try: new_sample = Sample.objects.create(**data) return redirect('/samples_list') except Exception as e: return render(request, 'add_sample.html', {'form': form, 'message': e}) return render(request, 'add_sample.html', {'form': form, 'message': 'coś nie tak w formularzu'})
'@type': 'Person', 'name': args.memberName, }, 'membershipNumber': args.membershipNumber, } if args.programName: metadata['programName'] = args.programName # Handle barcode generation image = None if args.barcode: barcode_type, barcode_data = args.barcode.split(':', 1) fp = io.BytesIO() barcode.generate(barcode_type, barcode_data, writer=SVGWriter(), output=fp) image = ('data:image/svg+xml;base64,%s' % (base64.b64encode(fp.getvalue()).decode('utf-8'))) fp.close() elif args.image: mime = magic.Magic(mime=True).from_file(args.image) with open(args.image, 'rb') as fp: image = 'data:%s;base64,%s' % (mime, base64.b64encode( fp.read()).decode('utf-8')) if image: metadata['image'] = image # Index token headers = {}
def generate_barcode(self, barcode_string): fp = StringIO() generate('code128', barcode_string, writer=BarcodeImageWriter(), output=fp) contents = fp.getvalue() return base64.standard_b64encode(contents)
def generate_barcode2(self, barcode_string, height, width): fp = StringIO() generate('CODE128', barcode_string, writer=ImageWriter(), output=fp) contents = fp.getvalue() return base64.standard_b64encode(contents)
def transform(tmpl_filename, html_filename, context): loader = TemplateLoader('templates', auto_reload=True) tmpl = loader.load(tmpl_filename) rendered = tmpl.generate(title=context['title'] , date=context['date'], images=context['images']).render('html', doctype='html') f = open(html_filename, 'w') f.write(rendered) f.close() if __name__ == '__main__': files = [] if not os.path.exists('output'): os.makedirs('output') f = open('eancodes.txt') for l in f.readlines(): l = l.strip() generate('EAN13', l, output=os.path.join('output', l)) files.append(l + '.svg') f.close() transform('index.tmpl', os.path.join('output', 'index.html'), {'title': 'Generated EAN CODES', 'date':'now', 'images': files})
async def create_badge(self, user, badge): avatar = user.avatar_url if user.avatar_url != "" else user.default_avatar_url username = user.display_name userid = user.id department = "GENERAL SUPPORT" if user.top_role.name == "@everyone" else user.top_role.name.upper( ) status = user.status if str(user.status) == "online": status = "ACTIVE" if str(user.status) == "offline": status = "COMPLETING TASK" if str(user.status) == "idle": status = "AWAITING INSTRUCTIONS" if str(user.status) == "dnd": status = "MIA" ext = "png" if "gif" in avatar: ext = "gif" await self.dl_image(avatar, ext) temp_barcode = generate("code39", userid, writer=ImageWriter(), output="data/badges/temp/bar_code_temp") await self.remove_white_barcode() fill = (0, 0, 0) # text colour fill if badge == "Q": fill = (255, 255, 255) await self.invert_barcode() template = Image.open(self.blank_template[badge]["loc"]) template = template.convert("RGBA") avatar = Image.open(self.files + "temp/temp." + ext) barcode = Image.open(self.files + "temp/bar_code_temp.png") barcode = barcode.convert("RGBA") barcode = barcode.resize((555, 125), Image.ANTIALIAS) template.paste(barcode, (400, 520), barcode) # font for user information font1 = ImageFont.truetype("data/badges/ARIALUNI.TTF", 30) # font for extra information font2 = ImageFont.truetype("data/badges/ARIALUNI.TTF", 24) draw = ImageDraw.Draw(template) # adds username draw.text((225, 330), str(username), fill=fill, font=font1) # adds ID Class draw.text( (225, 400), self.blank_template[badge]["code"] + "-" + str(user).split("#")[1], fill=fill, font=font1) # adds user id draw.text((250, 115), str(userid), fill=fill, font=font2) # adds user status draw.text((250, 175), status, fill=fill, font=font2) # adds department from top role draw.text((250, 235), department, fill=fill, font=font2) # adds user level draw.text((420, 475), "LEVEL " + str(len(user.roles)), fill="red", font=font1) # adds user level draw.text((60, 585), str(user.joined_at), fill=fill, font=font2) if ext == "gif": for image in glob.glob("data/badges/temp/tempgif/*"): os.remove(image) gif_list = [ frame.copy() for frame in ImageSequence.Iterator(avatar) ] img_list = [] num = 0 for frame in gif_list[:18]: watermark = frame.copy() watermark = watermark.convert("RGBA") watermark = watermark.resize((100, 100)) watermark.putalpha(128) id_image = frame.resize((165, 165)) template.paste(watermark, (845, 45, 945, 145), watermark) template.paste(id_image, (60, 95, 225, 260)) template.save("data/badges/temp/tempgif/{}.png".format( str(num))) num += 1 img_list = [ Image.open(file) for file in glob.glob("data/badges/temp/tempgif/*") ] template.save("data/badges/temp/tempbadge.gif", save_all=True, append_images=img_list, duration=1, loop=10) else: watermark = avatar.convert("RGBA") watermark.putalpha(128) watermark = watermark.resize((100, 100)) id_image = avatar.resize((165, 165)) template.paste(watermark, (845, 45, 945, 145), watermark) template.paste(id_image, (60, 95, 225, 260)) template.save("data/badges/temp/tempbadge.png")