def generatepdf417(): enc = encode(director, columns=15, security_level=7) name_417 = "first417.jpg" image_render = render_image(enc) image_render.show() image_render.save(name_417)
def _generate_png_ted(self, ted_string): unique = 1 filename = str(unique) + 'barcode.png' filepath = FILE_DIR + '/../temp/' + filename codes = pdf417.encode(ted_string, columns=10, security_level=5) image = pdf417.render_image(codes, scale=3, ratio=3, padding=5) # Pillow Image object image.save(filepath) return filepath
def generate_test_svg_ted(self, ted_string, filepath=FILE_DIR + '/../temp/test.svg'): unique = 1 filename = str(unique) + 'barcode.svg' filepath = FILE_DIR + '/../temp/' + filename codes = pdf417.encode(ted_string, security_level=5) svg = pdf417.render_svg(codes, scale=3, ratio=3) # ElementTree object svg.write(filepath) return filename
def application_form(request): if request.method == 'POST': def pr(name): return request.POST.get(name) doc = DocxTemplate("admission_form.docx") aadhar = None sclass = None if request.POST.get('aadhar') != '0': aadhar = request.POST.get('aadhar') if request.POST.get('coa') == '1': sclass = 'First' elif request.POST.get('coa') == '2': sclass = 'Second' elif request.POST.get('coa') == '3': sclass = 'Third' elif request.POST.get('coa') == '4': sclass = 'Fourth' p = request.POST.get('application_no') age = age_calc(pr('dob')) text = "Application no: " + request.POST.get('application_no') + "-Name: "+ request.POST.get('name') + "-Gender :" + request.POST.get('gender') + "-Date of birth :"+ str(request.POST.get('dob'))+ "-Class on admission: "+ str(request.POST.get('coa')) + "-Aadhar: "+ str(request.POST.get('aadhar'))+"-Name of father: "+ request.POST.get('father')+"-Name of mother: "+ request.POST.get('mother') +"-Mobile: "+str(request.POST.get('mob'))+"-Address: "+request.POST.get('address') # Convert to code words codes = encode(text) # Generate barcode as image image = render_image(codes) # Pillow Image object image.save('barcode.png') context = {'p1':p[:5] ,'p2':p[5:7] ,'p3': p[7:12] , 'name' : pr('name').upper(),'gender':pr('gender'),'a':aadhar,'father':pr('father'),'address':pr('address'),'mobile':pr('mob'),'mother':pr('mother'),'dob':pr('dob'),'age':age,'class':sclass} doc.render(context) doc.replace_media('dummy.png','barcode.png') doc.save("admission_form_print.docx") convertpdf("admission_form_print.docx") return redirect(report)
def xml_to_svg(xml_text): codes = encode(xml_text, columns=11) svg = render_svg(codes) svg.write('./templates/barcode.svg')
from pdf417 import render_svg, render_image, encode from pdf417.rendering import barcode_size, modules, rgb_to_hex from PIL.Image import Image from xml.etree.ElementTree import ElementTree codes = encode("hello world!") def test_rgb_to_hex(): assert rgb_to_hex((255, 0, 0)) == "#ff0000" assert rgb_to_hex((0, 255, 0)) == "#00ff00" assert rgb_to_hex((0, 0, 255)) == "#0000ff" assert rgb_to_hex((100, 0, 0)) == "#640000" assert rgb_to_hex((0, 100, 0)) == "#006400" assert rgb_to_hex((0, 0, 100)) == "#000064" assert rgb_to_hex((111, 222, 32)) == "#6fde20" def test_render_svg(): scale = 2 ratio = 4 description = "hi there" tree = render_svg(codes, scale=scale, ratio=ratio, description=description) assert isinstance(tree, ElementTree) assert tree.findtext("description") == description # Test expected size width, height = barcode_size(codes)
def _generate_svg_ted(self, ted_string): codes = pdf417.encode(ted_string, security_level=5) svg = pdf417.render_svg(codes, scale=3, ratio=3) # ElementTree object return svg
def genpdf417Func(textEncode, nameImage): enc = encode(textEncode, columns=10, security_level=8) image = render_image(enc, ratio=1, scale=2) return image.save(nameImage)
from pdf417 import encode, render_image, render_svg import base64 from io import BytesIO # Some data to encode text = """<DD xmlns=\"http://www.sii.cl/SiiDte\"><RE>11111111-1</RE><TD>52</TD><F>97</F><FE>2020-12-16</FE><RR>83659400-2</RR><RSR>Genérico</RSR><MNT>44000</MNT><IT1>[PT003108] Nuez Con Cáscara/ Inshell Wal</IT1><CAF version=\"1.0\"><DA><RE>76588454-3</RE><RS>DTEMITE LIMITADA</RS><TD>52</TD><RNG><D>1</D><H>50</H></RNG><FA>2016-07-06</FA><RSAPK><M>sH8h/4+7bUFGGxIk/4oAGZXNqORHHnUgkSlF7+EhF6fLtxUDZ5L7geHm48hX8AziucAGpZSDkE/IZCxvy+NYWw==</M><E>Aw==</E></RSAPK><IDK>100</IDK></DA><FRMA algoritmo=\"SHA1withRSA\">a8cGYqRIXwnFRTIaI8me3BVHCLWN0/8E5zSatOuc+DDevyy5aBxqk3PIEyVxtw/NzOqFkbCPvtvzIjAayt/GRg==</FRMA></CAF><TSTED>2021-01-04T09:31:48</TSTED></DD><FRMT algoritmo=\"SHA1withRSA\" xmlns=\"http://www.sii.cl/SiiDte\">pbyfs0Jcuv7P7XHLxWxAPfGfyDejHpSEe6lCzaXrVPS3OTY3xdB5JxhlvWaT4I55WyaTjO/1FMchrZ7bZN1m3w==</FRMT>""" cols = 12 while True: try: if cols == 31: break # Convert to code words codes = encode(text, cols) # Generate barcode as image image = render_image(codes) # Pillow Image object image.save("barcode.jpg") print(cols) break except: cols += 1
def send_to_sii(self): url = self.env.user.company_id.dte_url headers = { "apiKey": self.env.user.company_id.dte_hash, "CustomerCode": self.env.user.company_id.dte_customer_code } invoice = {} productLines = [] lineNumber = 1 netAmount = 0 exemtAmount = 0 countNotExempt = 0 #Main Validations self.validation_fields() move_line = [] if self.is_multiple_dispatch: move_line = self.dispatch_line_ids else: move_line = self.move_ids_without_package for item in move_line: haveExempt = False price_unit = item.sale_id.mapped('order_line').filtered( lambda a: a.product_id.id == item.product_id.id ).price_unit if self.is_multiple_dispatch else item.picking_id.sale_id.mapped( 'order_line').filtered( lambda a: a.product_id.id == item.product_id.id).price_unit amount = item.real_dispatch_qty * price_unit if self.is_multiple_dispatch else item.quantity_done * price_unit tax_ids = self.sale_id.mapped('order_line').filtered( lambda a: a.product_id.id == item.product_id.id).tax_id amount_tax = 0 for tax in tax_ids: if int(tax.amount) == 19: amount_tax += amount * (tax.amount / 100) break if len( self.sale_id.mapped('order_line').filtered( lambda a: a.product_id.id == item.product_id.id). mapped('tax_id')) == 0: haveExempt = True if haveExempt: exemtAmount += amount productLines.append({ "LineNumber": str(lineNumber), "ProductTypeCode": "EAN", "ProductCode": str(item.product_id.default_code), "ProductName": item.product_id.name, "ProductQuantity": str(item.real_dispatch_qty) if self.is_multiple_dispatch else str(item.quantity_done ), #segun DTEmite no es requerido int "UnitOfMeasure": str(item.product_id.uom_id.name), "ProductPrice": str(price_unit), #segun DTEmite no es requerido int "ProductDiscountPercent": "0", "DiscountAmount": "0", "Amount": str( self.roundclp(item.real_dispatch_qty * price_unit if self.is_multiple_dispatch else item.quantity_done * price_unit)), #str(int(amount)), "HaveExempt": haveExempt, "TypeOfExemptEnum": "1" #agregar campo a sale.order.line igual que acoount.invoice.line }) else: netAmount += self.roundclp(amount) productLines.append({ "LineNumber": str(lineNumber), "ProductTypeCode": "EAN", "ProductCode": str(item.product_id.default_code), "ProductName": item.product_id.name, "ProductQuantity": str(item.real_dispatch_qty) if self.is_multiple_dispatch else str(item.quantity_done), "UnitOfMeasure": str(item.product_id.uom_id.name), "ProductPrice": str(price_unit), "ProductDiscountPercent": "0", "DiscountAmount": "0", "Amount": str( self.roundclp(item.real_dispatch_qty * price_unit if self.is_multiple_dispatch else item.quantity_done * price_unit)), }) lineNumber += 1 if self.partner_id.phone: recipientPhone = str(self.partner_id.phone) elif self.partner_id.mobile: recipientPhone = str(self.partner_id.mobile) else: recipientPhone = '' self.write({ 'net_amount': str(self.roundclp(netAmount)), 'exempt_amount': str(self.roundclp(exemtAmount)), 'amount_tax': str(self.roundclp(amount_tax)), 'total': str( self.roundclp(netAmount + exemtAmount + self.sale_id.amount_tax)) }) invoice = { "dteType": self.dte_type_id.code, "createdDate": self.scheduled_date.strftime("%Y-%m-%d"), "expirationDate": self.date_due.strftime("%Y-%m-%d"), #No hay fecha de vencimiento "paymentType": int(self.method_of_payment), "dispatchType": str(self.dispatch_type), "transferIndication": str(self.transfer_indication), "transmitter": { "EnterpriseRut": re.sub( '[\.]', '', self.company_id.invoice_rut ), #re.sub('[\.]','', "76.991.487-0"), #self.env.user.company_id.invoice_rut, "EnterpriseActeco": self.company_activity_id.code, "EnterpriseAddressOrigin": self.env.user.company_id.street, "EnterpriseCity": self.env.user.company_id.city, "EnterpriseCommune": str(self.env.user.company_id.state_id.name), "EnterpriseName": self.env.user.company_id.partner_id.name, "EnterpriseTurn": self.env.user.company_id.partner_id.enterprise_turn, "EnterprisePhone": self.env.user.company_id.phone if self.env.user.company_id.phone else '' }, "recipient": { "EnterpriseRut": re.sub('[\.]', '', self.partner_id.invoice_rut), "EnterpriseAddressOrigin": self.partner_id.street[0:60], "EnterpriseCity": self.partner_id.city, "EnterpriseCommune": self.partner_id.state_id.name, "EnterpriseName": self.partner_id.name, "EnterpriseTurn": self.partner_id.enterprise_turn, "EnterprisePhone": recipientPhone }, "total": { "netAmount": self.net_amount, "exemptAmount": self.exempt_amount, "taxRate": "19", "taxtRateAmount": self.amount_tax, "totalAmount": self.total }, "lines": productLines, } # Add Refeences if self.references and len(self.references) > 0: refrenecesList = [] line_reference_number = 1 for item in self.references: refrenecesList.append({ "LineNumber": str(line_reference_number), "DocumentType": str(item.document_type_reference_id.id), "Folio": str(item.folio_reference), "Date": str(item.document_date), "Code": str(item.code_reference), "Reason": str(item.reason) }) line_reference_number += 1 invoice['references'] = refrenecesList #Add Additionals if len(self.observations_ids) > 0: additionals = [] for item in self.observations_ids: additionals.append(item.observations) invoice['additional'] = additionals r = requests.post(url, json=invoice, headers=headers) #raise models.ValidationError(json.dumps(invoice)) jr = json.loads(r.text) Jrkeys = jr.keys() if 'urlPdf' in Jrkeys and 'filePdf' in Jrkeys and 'folio' in Jrkeys and 'fileXml' in Jrkeys and 'ted' in Jrkeys: self.write({'pdf_url': jr['urlPdf']}) self.write({'dte_pdf': jr['filePdf']}) self.write({'dte_folio': jr['folio']}) self.write({'dte_xml': jr['fileXml']}) self.write({'dte_xml_sii': jr['fileXmlSII']}) cols = 12 while True: try: if cols == 31: break codes = encode(jr['ted'], cols) image = render_image(codes, scale=5, ratio=2) buffered = BytesIO() image.save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()) self.write({'ted': img_str}) break except: cols += 1 if 'status' in Jrkeys and 'title' in Jrkeys: raise models.ValidationError( 'Status: {} Title: {} Json: {}'.format(jr['status'], jr['title'], json.dumps(invoice))) elif 'message' in Jrkeys: raise models.ValidationError('Advertencia: {} Json: {}'.format( jr['message'], json.dumps(invoice)))