def barcode(request, model_name, coin_id, barcode_format='code128', image_format='png'): try: model = get_model(Coin._meta.app_label, '%s%s' % (model_name[0].upper(), model_name[1:].lower())) model = model.objects.get(pk=coin_id) except Coin.DoesNotExist: raise Http404 if image_format == 'jpeg': image_format = 'jpg' elif image_format not in ('png', 'jpg', 'gif'): image_format = 'png' if barcode_format == 'qr': barcode = createBarcodeDrawing( 'QR', value=model.qr_code, barHeight=90, barWidth=90, barBorder=0 ) else: barcode = createBarcodeDrawing( 'Code128', value=str(model.barcode), barWidth=1, quiet=False ) return HttpResponse( content=barcode.asString(image_format), mimetype='image/%s' % image_format )
def test1(self): '''test createBarcodeDrawing''' from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.graphics.barcode import getCodeNames for name in getCodeNames(): d = createBarcodeDrawing(name) for t in getattr(d.__class__,'_tests',[]): createBarcodeDrawing(name,value=t)
def run(): styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #for codeNames in code story.append(Paragraph('I2of5', styleN)) story.append(I2of5(1234, barWidth = inch*0.02, checksum=0)) story.append(Paragraph('MSI', styleN)) story.append(MSI(1234)) story.append(Paragraph('Codabar', styleN)) story.append(Codabar("A012345B", barWidth = inch*0.02)) story.append(Paragraph('Code 11', styleN)) story.append(Code11("01234545634563")) story.append(Paragraph('Code 39', styleN)) story.append(Standard39("A012345B%R")) story.append(Paragraph('Extended Code 39', styleN)) story.append(Extended39("A012345B}")) story.append(Paragraph('Code93', styleN)) story.append(Standard93("CODE 93")) story.append(Paragraph('Extended Code93', styleN)) story.append(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) story.append(Paragraph('Code 128', styleN)) c=Code128("AB-12345678") #, barWidth=0.005 * inch) #print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch) #print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch) story.append(c) story.append(Paragraph('USPS FIM', styleN)) story.append(FIM("A")) story.append(Paragraph('USPS POSTNET', styleN)) story.append(POSTNET('78247-1043')) story.append(Paragraph('USPS 4 State', styleN)) story.append(USPS_4State('01234567094987654321','01234567891')) from reportlab.graphics.barcode import createBarcodeDrawing story.append(Paragraph('EAN13', styleN)) bcd = createBarcodeDrawing('EAN13', value='123456789012') story.append(bcd) story.append(Paragraph('EAN8', styleN)) bcd = createBarcodeDrawing('EAN8', value='1234567') story.append(bcd) story.append(Paragraph('UPCA', styleN)) bcd = createBarcodeDrawing('UPCA', value='03600029145') story.append(bcd) story.append(Paragraph('USPS_4State', styleN)) bcd = createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891') story.append(bcd) story.append(Paragraph('Label Size', styleN)) story.append(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"')) story.append(Paragraph('Label Size', styleN)) story.append(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"')) c = Canvas('out.pdf') f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story, c) c.save() print('saved out.pdf')
def createbarcode(ch): data = ch.split(';') #print "DATA for Barcode", ch,data[1] #print "CODICE A BARRE " , data[1] if len(data[1]) ==13: bcd = createBarcodeDrawing('EAN13', value=data[1], width=float(data[2])*cm,height=float(data[3])*cm) elif len(data[1]) == 8: bcd = createBarcodeDrawing('EAN8', value=data[1], width=float(data[2])*cm,height=float(data[3])*cm) else: bcd = createBarcodeDrawing('EAN13', value=data[1], width=float(data[2])*cm,height=float(data[3])*cm) #bcd = createBarcodeDrawing('EAN13', value="8002705005009", width=float(data[2])*cm,height=float(data[3])*cm) return bcd
def _print_code(self, index, order, code): if self.draw_y - self.TICKET_HEIGHT < max(self.INTERTICKET_MARGIN, self.PAGE_MARGIN_Y): self.canvas.showPage() self.canvas.setFont("Helvetica", 9, 8) page_id_text = "Sivu %d" % self.canvas._pageNumber if order.reference_number: page_id_text += " - Viitenumero: %s" % order.reference_number self.canvas.drawString(self.PAGE_MARGIN_X, self.PAGE_HEIGHT - self.PAGE_MARGIN_Y, page_id_text) self.draw_y = self._align_draw_y(self.PAGE_HEIGHT - self.PAGE_MARGIN_Y - 10 * mm) ticket_width = self.PAGE_WIDTH - 2 * self.PAGE_MARGIN_X with save_state(self.canvas): self.canvas.translate(self.PAGE_MARGIN_X, self.draw_y - self.TICKET_HEIGHT) self.canvas.roundRect(0, 0, ticket_width, self.TICKET_HEIGHT, 0.15 * cm) linear_barcode_width = self.PAGE_WIDTH * 0.5 barcode_height = 0.5 * self.TICKET_HEIGHT linear_barcode = createBarcodeDrawing( "Standard39", checksum=False, # Seems to be extraneous (using Android's Barcode reader app), quiet=False, # We'll deal with these ourselves value=code.full_code, width=linear_barcode_width, height=barcode_height ) barcode_bottom_y = self.TICKET_HEIGHT - 3 * mm - barcode_height draw_on_pdf(linear_barcode, self.canvas, self.INTRA_TICKET_X_MARGIN, barcode_bottom_y) qr_barcode_size = self.TICKET_HEIGHT - 6 * mm qr_barcode = createBarcodeDrawing( "QR", value=code.full_code, barBorder=0, # We'll deal with these ourselves width=qr_barcode_size, height=qr_barcode_size ) draw_on_pdf(qr_barcode, self.canvas, ticket_width - self.INTRA_TICKET_X_MARGIN - qr_barcode_size, 3 * mm) y = draw_multiline( self.canvas, self.INTRA_TICKET_X_MARGIN, 11 * mm, 9, 12, [ u"%s \u2014 %s" % (code.product_text, code.full_code), code.literate_code ] ) self.draw_y -= (self.INTERTICKET_MARGIN + self.TICKET_HEIGHT)
def generate_image(self, street, number, house_id): options = {'width': 500, 'height': 500} current_url = WEBSITE_URL + ( street + "-" + number + "-" + str(house_id)).lower() ret_val = createBarcodeDrawing('QR', value=str(current_url), **options) image = base64.encodestring(ret_val.asString('png')) self.write({'image': image})
def __init__(self, text_value, *args, **kwargs): barcode = createBarcodeDrawing("Code128", value=text_value.encode("utf-8"), barHeight=10*mm, width=80*mm) Drawing.__init__(self, barcode.width, barcode.height, *args, **kwargs) self.add(barcode, name="barcode")
def print_barcode_page(request, page_id): bcp = get_object_or_404(BarcodePage, id=page_id) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % slugify(bcp.titre) # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) width, height = A4 p.drawCentredString(width/2, height-50, bcp.titre) produits = bcp.produits.all() for idx, prod in enumerate(produits): row = idx%7 col = idx//7 h = 110 w = 180 v_offset = height-80 h_offset = 60 img_offset = 80 text_offset = 10 d = createBarcodeDrawing("EAN13",value=str(prod.ean)) p.drawString(h_offset+text_offset+col*w, v_offset-row*h, prod.nom) renderPDF.draw(d, p, h_offset+col*w, v_offset-img_offset-row*h) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
def pdf(self, id): buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 800, "Hello world.") barcode = createBarcodeDrawing('Code128', value=id, barHeight=10*mm, humanReadable=True) barcode.drawOn(p, 100, 700) # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf_data = buffer.getvalue() buffer.close() return wrap_pdf_response(pdf_data, "boarding_pass.pdf")
def draw_code128_questionnaire_id(canvas, survey, id): # Only supports ascii for now (see also defs.py) barcode_value = unicode(id).encode('ascii') barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = defs.corner_mark_left barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x + defs.code128_hpad # The barcode should be flush left. barcode_x = barcode_x renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + \ defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def generate(request, code, barcode_type='Standard39', auto_print=True): """ Returns a PDF Barcode using ReportLab """ from reportlab.graphics.shapes import String from reportlab.graphics import renderPDF from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.pdfbase import pdfdoc from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'inline; filename=%s.pdf' % (code,) # Config import bcp.settings as bcp_settings font_size = bcp_settings.FONT_SIZE bar_height = bcp_settings.BAR_HEIGHT bar_width = bcp_settings.BAR_WIDTH font_name = bcp_settings.FONT_NAME font_path = bcp_settings.FONT_PATH try: # If this is extended to different barcode types, then these options will need to be specified differently, eg not all formats support checksum. bc = createBarcodeDrawing(barcode_type, barHeight=bar_height, barWidth=bar_width, value=str(code), isoScale=True, quiet=bcp_settings.BAR_QUIET, checksum=bcp_settings.BAR_CHECKSUM,) except KeyError, e: return HttpResponseBadRequest('Barcode Generation Failed: %s' % (e))
def part_label(request, part_number): part = get_object_or_404(Part, part_number=part_number) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="label.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) p.setPageSize((105*mm, 26*mm)) # Draw Part Number p.setFont("Helvetica", 20) p.drawCentredString(52*mm, 18*mm, part.part_number) barcode = createBarcodeDrawing('Code128', value=part.part_number, barWidth=0.33*mm, barHeight=13*mm, humanReadable=False) barcode.drawOn(p, 1*mm, 2*mm) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) #action.send(request.user, verb="generated a label", target=report) return response
def draw_code128_global_id(canvas, survey): if survey.global_id is None: raise AssertionError # Only allow ascii barcode_value = survey.global_id.encode('ascii') barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = (survey.defs.paper_width - defs.corner_mark_right + defs.corner_mark_left) / 2 barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x # Center barcode_x = barcode_x - barcode.width / mm / 2.0 renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def gen_form(code, showCodes): value = request.args.get('value', '') count = request.args.get('count', '') scale = request.args.get('scale', '5') action = request.args.get('action', '') if len(scale) == 0 or not scale.isdigit(): scale = 5 if len(value) == 0: return render(scale, showCodes, code) try: if not (code in getCodeNames()): flash("Code "+code+" not supported allowed are : " + str(getCodeNames())) return render(scale, True, None, count, value) if value.isdigit() and count.isdigit(): if int(count) > 1000 and action == 'Generate PDF': flash("Please enter a lower count - maximum is 1000.") return render(scale, showCodes, code, count, value) dr = createBarcodeDrawing(code, value=value, humanReadable=True) if action == 'Generate PDF': if value.isdigit() and count.isdigit(): return redirect(url_for('pdflist', code=code, scale=scale, start=value, count=count)) else: return redirect(url_for('pdf', code=code, scale=scale, value=value)) else: return render(scale, showCodes, code, count, value, True) except: flash("Error while generating a " + code + ": " + str(sys.exc_info()[0])) return render(scale, showCodes, code, count, value)
def draw_code128_sdaps_info(canvas, survey, page): # The page number is one based here already # The survey_id is a 32bit number, which means we need # 10 decimal digits to encode it, then we need to encode the # the page with at least 3 digits(just in case someone is insane enough # to have a questionnaire with more than 99 pages. # So use 10+4 digits barcode_value = "%010d%04d" % (survey.survey_id, page) barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = survey.defs.paper_width - defs.corner_mark_right barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x - defs.code128_hpad # The barcode should be flush left. barcode_x = barcode_x - barcode.width / mm renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def location_scan_sheet(request): locations = InventoryLocation.objects.all().order_by('location_code') response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="locations.pdf"' p = canvas.Canvas(response) p.setPageSize((215*mm, 275*mm)) i = 260 column_a = [15] column_b = [65] column_c = [115] column_d = [165] horizontal = column_a for location in locations: p.setFont("Helvetica", 15) #p.drawCentredString(horizontal[0]*mm, (i+3)*mm, location.location_code) barcode = createBarcodeDrawing('Code128', value=location.location_code, barWidth=0.25*mm, barHeight=8*mm, humanReadable=True) barcode.drawOn(p, horizontal[0]*mm, (i)*mm) i -= 16 if i < 2: i = 260 if horizontal == column_a: horizontal = column_b elif horizontal == column_b: horizontal = column_c elif horizontal == column_c: horizontal = column_d else: horizontal = column_a p.showPage() p.save() return response
def barcode(self, type, value, width=600, height=100, humanreadable=0): width, height = int(width), int(height) humanreadable = bool(humanreadable) barcode_obj = createBarcodeDrawing( type, value=value, format='png', width=width, height=height, humanReadable=humanreadable ) return base64.encodestring(barcode_obj.asString('png'))
def __init__(self, text_value, *args, **kw): barcode = createBarcodeDrawing( 'Code128', value=text_value, barHeight=10 * mm, humanReadable=True) Drawing.__init__(self, barcode.width, barcode.height, *args, **kw) self.add(barcode, name='barcode')
def draw_contents(self,c,xpos,ypos,width,height): # Generate barcode bc=barcode.createBarcodeDrawing('Extended93',width=width, height=40, value=self.code,checksum=0,humanReadable=True,fontSize=2*mm,fontName='Helvetica') bc.drawOn(c,xpos,ypos+5*self.units) c.setFont("Helvetica", 6) c.drawCentredString(xpos+width/2, ypos+23*self.units,self.ref) c.setFont("Helvetica", 4) c.drawCentredString(xpos+width/2, ypos+20*self.units,self.desc)
def get_image(self, value, width, hight, hr, code='QR'): options = {} if width:options['width'] = width if hight:options['hight'] = hight if hr:options['humanReadable'] = hr try: ret_val = createBarcodeDrawing(code, value=str(value), **options) except Exception, e: raise osv.except_osv('Error', e)
def genBarcode(code, value, canvas, scale): dr = createBarcodeDrawing(code, value=value, humanReadable=True) dr.renderScale = scale bounds = dr.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] dr.drawOn(canvas, (297*mm)/2-width*scale/2, (210*mm)/2-height*scale/2) canvas.drawString(1*mm, 1*mm, "generated at "+str(datetime.now()) + " from "+request.url) canvas.showPage()
def printBarcode(self, value, width, height): try: width, height = int(width), int(height) barcode = createBarcodeDrawing( 'EAN13', value=value, format='png', width=width, height=height) barcode = barcode.asString('png') barcode = barcode.encode('base64', 'strict') except (ValueError, AttributeError): raise exceptions.Warning(_('Cannot convert into barcode.')) return barcode
def get_barcode_image(value, width = False, hight = False, hr = True, code = 'QR'): """ genrating image for barcode """ options = {} if width:options['width'] = width if hight:options['hight'] = hight if hr:options['humanReadable'] = hr try: ret_val = createBarcodeDrawing(code, value = str(value), **options) except Exception, e: raise osv.except_osv('Error', e)
def get_image_code(value, width, height, hr=False, code='QR'): """ generating image for barcode """ options = {} if width:options['width'] = width if height:options['height'] = height if hr:options['humanReadable'] = hr try: ret_val = createBarcodeDrawing(code, value=unicode(value), **options) except Exception, e: raise osv.except_osv('Error', e)
def barcode(value): if type(value)==unicode and len(value)==12 and value.isdigit(): d = createBarcodeDrawing("EAN13", value=str(value)) s = renderSVG.drawToString(d) lines = s.split('\n') outlines = [] outlines.append(lines[4]) outlines.extend(lines[7:]) return mark_safe("\n".join(outlines)) else: return type(value)
def generate_pdf(self, ticket): """ Generate PDF file. :param ticket Ticket: ticket object :return: path to output PDF """ # Get configurable text title_text = _(Config.get('ticket_title', None)) # Setup styles styles = getSampleStyleSheet() doc = SimpleDocTemplate(self.pdf_path, pagesize=letter, topMargin=5*mm, # NOTE We don't want to offend some printers by setting too small # pagesize. rightMargin=(letter[0] - self.width*mm - 2*mm), bottomMargin=5*mm, leftMargin=2*mm) # Build document contents story = [] if title_text: story.append(Paragraph('{}'.format(title_text), styles['Title'])) # Creation and expiration date story.append(Paragraph('{}: {}<br/>{}: {}'.format( _('Cas vydani'), ticket.created.strftime('%d.%m.%Y %H:%M'), _('Platnost do'), ticket.expires().strftime('%d.%m.%Y %H:%M')), styles['Normal'])) story.append(Spacer(width=1, height=10*mm)) # Barcode (Standard39) barcode = createBarcodeDrawing('Standard39', value=ticket.code, checksum=0, quiet=False, # don't use quiet zones on left and right barWidth=0.25*mm, barHeight=30*mm, humanReadable = True) # Scale barcode down to fit the page s = float(self.width*mm - 8*mm) / float(barcode.width) barcode.scale(s, s) story.append(barcode) # Save the PDF doc.build(story)
def barcode(self, barcode_type, value, width=600, height=100, humanreadable=0): if barcode_type == "UPCA" and len(value) in (11, 12, 13): barcode_type = "EAN13" if len(value) in (11, 12): value = "0%s" % value try: width, height, humanreadable = int(width), int(height), bool(int(humanreadable)) barcode = createBarcodeDrawing( barcode_type, value=value, format="png", width=width, height=height, humanReadable=humanreadable ) return barcode.asString("png") except (ValueError, AttributeError): raise ValueError("Cannot convert into barcode.")
def img(code, value, scale): try: dr = createBarcodeDrawing(code, value=str(value), humanReadable=True) dr.renderScale = scale d = Drawing(dr.width*scale, dr.height*scale) d.add(dr) d.renderScale = scale response = make_response(d.asString('png')) response.mimetype = 'image/png' return response except: return send_from_directory(os.path.join(app.root_path, 'static'), 'error.png', mimetype='image/png')
def doc_overlay(request, document_uuid, lot_number, qrcode=True): report = Report.objects.get(lot_number=lot_number) document = Document.objects.get(uuid=document_uuid) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="inspection_report.pdf"' outputPDF = PdfFileWriter() packet = StringIO() # read your existing PDF f = urlopen(Request(document.file.url)).read() mem = StringIO(f) existing_pdf = PdfFileReader(mem) pages = existing_pdf.getNumPages() first_page = existing_pdf.getPage(0) width = float(first_page.mediaBox.getWidth()) height = float(first_page.mediaBox.getHeight()) # create a new PDF with Reportlab p = canvas.Canvas(packet, pagesize=letter) #p.setFillColorRGB(255,255,255) #p.rect(0*mm, 271*mm, 205*mm, 12*mm, fill=1, stroke=0) p.setFillColorRGB(0,0,0) p.setFont("Helvetica", 7) p.drawCentredString(width/2.0,height-9.0, "%s LOT # %s / %s (doc# %s)" % (settings.PDF_COMPANY_SHORT_NAME, report.lot_number, str(report.created_at.date()), document.uuid)) barcode = createBarcodeDrawing('QR', value="%s%s" % (request.META['HTTP_HOST'], report.get_absolute_url())) barcode.drawOn(p,175*mm, 10*mm) p.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # add the "watermark" (which is the new pdf) on the existing page for x in range(0,pages): page = existing_pdf.getPage(x) page.mergePage(new_pdf.getPage(0)) outputPDF.addPage(page) # finally, write "output" to a real file outputPDF.write(response) #f.close() action.send(request.user, verb="viewed document", action_object=document, target=report) return response
def barcode(self, barcode_type, value, width=600, height=100, humanreadable=0): kwargs = {} if barcode_type == 'UPCA' and len(value) in (11, 12, 13): barcode_type = 'EAN13' if len(value) in (11, 12): value = '0%s' % value elif barcode_type == 'auto': symbology_guess = {8: 'EAN8', 13: 'EAN13'} barcode_type = symbology_guess.get(len(value), 'Code128') # add QR_quiet type for QR type with no border (not in 13.0 since there is quiet argument) if barcode_type == 'QR_quiet': kwargs['quiet'] = 1 kwargs['barBorder'] = 0 barcode_type = 'QR' try: width, height, humanreadable = int(width), int(height), bool( int(humanreadable)) barcode = createBarcodeDrawing(barcode_type, value=value, format='png', width=width, height=height, humanReadable=humanreadable, **kwargs) return barcode.asString('png') except (ValueError, AttributeError): if barcode_type == 'Code128': raise ValueError("Cannot convert into barcode.") else: return self.barcode('Code128', value, width=width, height=height, humanreadable=humanreadable)
def barcode(self, barcode_type, value, width=600, height=100, humanreadable=0): if barcode_type == 'UPCA' and len(value) in (11, 12, 13): barcode_type = 'EAN13' if len(value) in (11, 12): value = '0%s' % value try: width, height, humanreadable = int(width), int(height), bool( int(humanreadable)) barcode = createBarcodeDrawing(barcode_type, value=value, format='png', width=width, height=height, humanReadable=humanreadable) return barcode.asString('png') except (ValueError, AttributeError): raise ValueError("Cannot convert into barcode.")
def get_code128_barcode(self, value, width, barWidth=(0.05 * units.inch) / 2, fontSize=12, humanReadable=True): # El valor por default de fontSize=60 barcode = createBarcodeDrawing('Code128', value=value, barWidth=barWidth, fontSize=fontSize, humanReadable=humanReadable) drawing_width = width barcode_scale = drawing_width / barcode.width drawing_height = barcode.height * barcode_scale drawing = Drawing(drawing_width, drawing_height) drawing.scale(barcode_scale, barcode_scale) drawing.add(barcode, name='barcode') barcode_encode = b64encode(renderPM.drawToString(drawing, fmt='PNG')) barcode_str = '<img style="width:320px;height:80px;" src="data:image/png;base64,{0} : ">'.format( barcode_encode) return barcode_str
def barcode(self, value, code='Code128', drawOpts=None, htmlAttrs=None): """ Generate a <img /> tag with embedded barcode Params: - value: barcode value, must be valid for barcode type - code: barcode type, as per reportlab.graphics.barcode.getCodes() - drawOpts: options for the reportlab barcode - htmlAttrs: attributes for <img /> tag """ drawOpts = (drawOpts or {}) imgtype = drawOpts.pop('format', 'png') attrs = (htmlAttrs or {}) drawOpts['value'] = value for k in ('width', 'height'): # Attempt to unify drawing and image sizes to prevent accidental # scaling, and reduce parameter duplication if k in drawOpts and k not in attrs: attrs[k] = "{0}px".format(drawOpts[k]) elif k in attrs and k not in drawOpts: # reportlab expects a float value = str(attrs[k]) if value.endswith("px"): value = value[:-2].strip() try: value = float(value) except ValueError: # Ignore values that we can't handle pass else: drawOpts[k] = value data = createBarcodeDrawing(code, **drawOpts).asString(imgtype) attrs['src'] = "data:image/{1};base64,{0}".format( data.encode('base64'), imgtype, ) return HTML(Element('img', attrs))
def draw_header(p, rs): y = 10 + 6 p.drawImage(path + 'images/logo_header_urbano.jpg', (10) * mm, -(y * mm), 29 * mm, 9 * mm, mask=None) y += 5 barcode = createBarcodeDrawing('Code128', value=rs['reclamo'], barWidth=0.2 * mm, width=100 * mm, barHeight=11 * mm, fontSize=8, humanReadable=False, fontName='xcalibri', borderWidth=1) barcode.drawOn(p, 105 * mm, -((y - 5) * mm)) p.setFont('xcalibri', 12) p.drawCentredString( 155 * mm, -((y - 1.5) * mm), codecs.decode(valida_none(str(rs['reclamo'])), 'latin-1'))
def barcode(self, barcode_type, value, width=600, height=100, humanreadable=0, quiet=1, mask=None): if barcode_type == 'UPCA' and len(value) in (11, 12, 13): barcode_type = 'EAN13' if len(value) in (11, 12): value = '0%s' % value elif barcode_type == 'auto': symbology_guess = {8: 'EAN8', 13: 'EAN13'} barcode_type = symbology_guess.get(len(value), 'Code128') try: width, height, humanreadable, quiet = int(width), int(height), bool(int(humanreadable)), bool(int(quiet)) # for `QR` type, `quiet` is not supported. And is simply ignored. # But we can use `barBorder` to get a similar behaviour. bar_border = 4 if barcode_type == 'QR' and quiet: bar_border = 0 barcode = createBarcodeDrawing( barcode_type, value=value, format='png', width=width, height=height, humanReadable=humanreadable, quiet=quiet, barBorder=bar_border ) # If a mask is asked and it is available, call its function to # post-process the generated QR-code image if mask: available_masks = self.get_available_barcode_masks() mask_to_apply = available_masks.get(mask) if mask_to_apply: mask_to_apply(width, height, barcode) return barcode.asString('png') except (ValueError, AttributeError): if barcode_type == 'Code128': raise ValueError("Cannot convert into barcode.") else: return self.barcode('Code128', value, width=width, height=height, humanreadable=humanreadable, quiet=quiet)
def report_barcode(self, type, value, width=600, height=100, humanreadable=0): """Contoller able to render barcode images thanks to reportlab. Samples: <img t-att-src="'/report/barcode/QR/%s' % o.name"/> <img t-att-src="'/report/barcode/?type=%s&value=%s&width=%s&height=%s' % ('QR', o.name, 200, 200)"/> :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39', 'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93', 'UPCA', 'USPS_4State' :param humanreadable: Accepted values: 0 (default) or 1. 1 will insert the readable value at the bottom of the output image """ try: width, height, humanreadable = int(width), int(height), bool(humanreadable) barcode = createBarcodeDrawing( type, value=value, format='png', width=width, height=height, humanReadable = humanreadable ) barcode = barcode.asString('png') except (ValueError, AttributeError): raise exceptions.HTTPException(description='Cannot convert into barcode.') return request.make_response(barcode, headers=[('Content-Type', 'image/png')])
def __init__(self, text_value, *args, **kw): barcode = createBarcodeDrawing('Code128', value=text_value, barHeight=10*mm, humanReadable=True) Drawing.__init__(self,barcode.width,barcode.height,*args,**kw) self.add(barcode, name='barcode')
def draw_contenido(p, index, value): global y global x global columnax global columnay if ((index-1) % NX == 0 ): y = ealto * columnay +20 x = 0 columnax = 0 columnay += 1 else: columnax += 1 x = eancho * columnax if (columnax == NX): columnax = 0 if (columnay == NY): columnay = 0 #print ealto p.drawImage('/sistemas/weburbano/public_html/images/logo.jpg', (x+10)*mm, -((y-11)*mm), 25*mm, 8*mm, mask=None) barcode = createBarcodeDrawing('Code128', value = value['gui_numero'], barHeight= 10,barWidth = 0.015 * inch, fontSize = 8, humanReadable = True ) ''' barcode.drawOn(p, ((x+1) * mm), -((y-12)*mm)) #dibuja la barra #p.rect((x+6)*mm, -(y*mm), eancho*mm, ealto*mm, 1, 0)#dibuja el rectangulo p.setFont('xcalibriBd', 6) p.drawString((x+7)*mm, -((y-11)*mm), codecs.decode(valida_none(value['cli_nombre'][:45]), 'latin-1')) #p.drawRightString((x+53)*mm, -((y-13)*mm), codecs.decode(valida_none(value['serie']), 'latin-1')) p.setFont('xcalibri', 5) p.drawRightString((x+50)*mm, -((y-4)*mm), codecs.decode(valida_none(value['distrito']), 'latin-1')) calle = codecs.decode(valida_none((value['dir_calle']+' '+value['dir_referen'])[:200] ), 'latin-1') parrafo = Paragraph(calle, styleN) ''' p.rect((x+10)*mm, -((y+32)*mm), 95*mm, 42*mm, 1, 0) #p.line((16-x)*mm, (160-y)*mm, (16+x)*mm, (118-y)*mm) #linea vertical p.rect((x+110)*mm, -((y+32)*mm), 95*mm, 42*mm, 1, 0) #p.line((116-x)*mm, (160-y)*mm, (116+x)*mm, (118-y)*mm) #linea vertical p.rect((x+10)*mm, -((y+77)*mm), 95*mm, 42*mm, 1, 0) #p.line((16-x)*mm, (115-y)*mm, (16+x)*mm, (73-y)*mm) #linea vertical p.rect((x+10)*mm, -((y+122)*mm), 95*mm, 42*mm, 1, 0) p.line((16-x)*mm, (115-y)*mm, (16+x)*mm, (30-y)*mm) #linea vertical #p.line(50,(x-10)*mm,50,(y+150)*mm) #p.line((17-x)*mm, (160-y)*mm, (17+x)*mm, (118-y)*mm) '''
def run(): styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] storyAdd = story.append #for codeNames in code storyAdd(Paragraph('I2of5', styleN)) storyAdd(I2of5(1234, barWidth=inch * 0.02, checksum=0)) storyAdd(Paragraph('MSI', styleN)) storyAdd(MSI(1234)) storyAdd(Paragraph('Codabar', styleN)) storyAdd(Codabar("A012345B", barWidth=inch * 0.02)) storyAdd(Paragraph('Code 11', styleN)) storyAdd(Code11("01234545634563")) storyAdd(Paragraph('Code 39', styleN)) storyAdd(Standard39("A012345B%R")) storyAdd(Paragraph('Extended Code 39', styleN)) storyAdd(Extended39("A012345B}")) storyAdd(Paragraph('Code93', styleN)) storyAdd(Standard93("CODE 93")) storyAdd(Paragraph('Extended Code93', styleN)) storyAdd(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) storyAdd(Paragraph('Code 128', styleN)) storyAdd(Code128("AB-12345678")) storyAdd(Paragraph('Code 128 Auto', styleN)) storyAdd(Code128Auto("AB-12345678")) storyAdd(Paragraph('USPS FIM', styleN)) storyAdd(FIM("A")) storyAdd(Paragraph('USPS POSTNET', styleN)) storyAdd(POSTNET('78247-1043')) storyAdd(Paragraph('USPS 4 State', styleN)) storyAdd(USPS_4State('01234567094987654321', '01234567891')) from reportlab.graphics.barcode import createBarcodeDrawing storyAdd(Paragraph('EAN13', styleN)) storyAdd(createBarcodeDrawing('EAN13', value='123456789012')) storyAdd(Paragraph('EAN13 quiet=False', styleN)) storyAdd(createBarcodeDrawing('EAN13', value='123456789012', quiet=False)) storyAdd(Paragraph('EAN8', styleN)) storyAdd(createBarcodeDrawing('EAN8', value='1234567')) storyAdd(PageBreak()) storyAdd(Paragraph('EAN5 price=True', styleN)) storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True)) storyAdd(Paragraph('EAN5 price=True quiet=False', styleN)) storyAdd( createBarcodeDrawing('EAN5', value='11299', price=True, quiet=False)) storyAdd(Paragraph('EAN5 price=False', styleN)) storyAdd(createBarcodeDrawing('EAN5', value='11299', price=False)) storyAdd(Paragraph('ISBN alone', styleN)) storyAdd(createBarcodeDrawing('ISBN', value='9781565924796')) storyAdd(Paragraph('ISBN with ean5 price', styleN)) storyAdd(createBarcodeDrawing('ISBN', value='9781565924796', price='01299')) storyAdd(Paragraph('ISBN with ean5 price, quiet=False', styleN)) storyAdd( createBarcodeDrawing('ISBN', value='9781565924796', price='01299', quiet=False)) storyAdd(Paragraph('UPCA', styleN)) storyAdd(createBarcodeDrawing('UPCA', value='03600029145')) storyAdd(Paragraph('USPS_4State', styleN)) storyAdd( createBarcodeDrawing('USPS_4State', value='01234567094987654321', routing='01234567891')) storyAdd(Paragraph('QR', styleN)) storyAdd(createBarcodeDrawing('QR', value='01234567094987654321')) storyAdd(Paragraph('QR', styleN)) storyAdd( createBarcodeDrawing('QR', value='01234567094987654321', x=30, y=50)) storyAdd(Paragraph('QR in drawing at (0,0)', styleN)) d = Drawing(100, 100) d.add( Rect(0, 0, 100, 100, strokeWidth=1, strokeColor=colors.red, fillColor=None)) d.add(QrCodeWidget(value='01234567094987654321')) storyAdd(d) storyAdd(Paragraph('QR in drawing at (10,10)', styleN)) d = Drawing(100, 100) d.add( Rect(0, 0, 100, 100, strokeWidth=1, strokeColor=colors.red, fillColor=None)) d.add(Line(7.5, 10, 12.5, 10, strokeWidth=0.5, strokeColor=colors.blue)) d.add(Line(10, 7.5, 10, 12.5, strokeWidth=0.5, strokeColor=colors.blue)) d.add(QrCodeWidget(value='01234567094987654321', x=10, y=10)) storyAdd(d) storyAdd(Paragraph('Label Size', styleN)) storyAdd(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"')) storyAdd(Paragraph('Label Size', styleN)) storyAdd(XBox((1.75) * inch, .5 * inch, '1/2x1-3/4"')) SimpleDocTemplate('out.pdf').build(story) print('saved out.pdf')
def memo(request, message_id): ''' Función para descarga de memorándums en PDF ''' response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = u'attachment; filename=Memorándum.pdf; pagesize=A4' elementos = [] doc = SimpleDocTemplate(response) style = getSampleStyleSheet() style2 = getSampleStyleSheet() styleFecha = getSampleStyleSheet() styleEncabezado = getSampleStyleSheet() fechas = datetime.datetime.today() mes = fecha.NormalDate().monthName() dia = fecha.NormalDate().dayOfWeekName() salto = '<br />' txtFecha = '%s, %s DE %s DE %s' % (dia.upper(), fechas.day, mes.upper(), fechas.year) styleF = styleFecha['Normal'] styleF.fontSize = 8 styleF.fontName = 'Helvetica' styleF.alignment = TA_RIGHT fechaV = Paragraph(txtFecha, styleF) elementos.append(fechaV) elementos.append(Spacer(1, 5)) #-- Espacio para poner el encabezado con la clase Canvas elementos.append(Spacer(1, 75)) from django_messages.models import Message memo = Message.objects.get(id=message_id) txtTitulo = u'MEMORÁNDUM%s' % (salto) if memo.tipo == 'Circular': txtTitulo = 'MEMORÁNDUM CIRCULAR' titulo = style['Heading1'] titulo.fontSize = 12 titulo.fontName = 'Helvetica-Bold' titulo.alignment = TA_CENTER tituloV = Paragraph(txtTitulo, titulo) elementos.append(tituloV) elementos.append(Spacer(1, 5)) x = [ ('BOX', (0, 0), (-1, -1), 0.50, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), #('TOPPADDING', (0,0), (-1,-1), 1), #('BOTTOMPADDING', (0,0), (-1,-1), 2), ('GRID', (0, 0), (-1, -1), 0.50, colors.black), #('FONT', (0,0), (-1,-1), "Helvetica", 8), ('FONT', (0, 0), (-1, -1), "Helvetica", 6), ] identificador = '%s.%s.%s - %d %s' % ( memo.sender.usuarios.persona.cargo_principal.dependencia.dependencia. nivel, memo.sender.usuarios.persona.cargo_principal.dependencia.nivel, memo.sender.usuarios.persona.cargo_principal.dependencia.siglas, memo.id, salto) de = u'<b>DE: </b> %s %s' % (memo.sender, salto) para = '' memos = Message.objects.filter(codigo=memo.codigo) for memorandums in memos: para = u'%s, %s' % (memorandums.recipient, para) para = u'<b>PARA: </b> %s %s' % (para, salto) para = u'<b>ASUNTO: </b> %s %s' % (para, salto) memo_mes = fecha.NormalDate(memo.sent_at).monthName() memo_dia = fecha.NormalDate(memo.sent_at).dayOfWeekName() enviado = '<b>FECHA:</b> %s, %s de %s de %s a las %s:%s:%s %s' % ( memo_dia, memo.sent_at.day, memo_mes, memo.sent_at.year, memo.sent_at.time().hour, memo.sent_at.time().minute, memo.sent_at.time().second, salto) txtInfo = '%s %s %s %s' % (identificador, para, de, enviado) # Estilo txtInfo info = style['Normal'] info.fontSize = 12 info.alignment = TA_LEFT info.fontName = 'Helvetica' infoV = Paragraph(txtInfo, info) elementos.append(infoV) elementos.append(Spacer(1, 10)) autoescape = None autoescape = autoescape and not isinstance(memo.body, SafeData) memo.body = normalize_newlines(memo.body) texto = salto + mark_safe(memo.body.replace('\n', '<br />')) #---> Estilo de la variable texto parrafo = style2['Normal'] parrafo.fontsize = 12 parrafo.fontName = 'Helvetica' parrafo.alignment = TA_JUSTIFY parrafo.spaceBefore = 5 parrafo.firstLineIndent = 20 Parrafo1 = Paragraph(u'%s' % (texto), parrafo) elementos.append(Parrafo1) elementos.append(Spacer(3, 30)) # Inicio código de barras codigoBarra_style = getSampleStyleSheet() codigoBarra = codigoBarra_style['Normal'] codigoBarra.fontSize = 12 codigoBarra.fontName = 'Courier' codigoBarra.alignment = TA_RIGHT st = createBarcodeDrawing('Code128', value=str(memo.codigo), barWidth=0.040 * cm, barHeight=0.500 * cm, lquiet=11.950 * cm) elementos.append(st) txtCodigoBarra = Paragraph(str(memo.codigo), codigoBarra) elementos.append(txtCodigoBarra) # Fin código de barras doc.build(elementos, canvasmaker=NumeroDePagina, onFirstPage=encabezado_constancia) return response
def print_barcode_label_old(isbn='', booktitle='', author='', ourprice=0, listprice=0, num_copies=1): import sys print(type(isbn), type(isbn1), type(booktitle), file=sys.stderr) print(isbn, booktitle, author, ourprice, listprice, num_copies, file=sys.stderr) rl_config.warnOnMissingFontGlyphs = 1 try: registerFont(TTFont('Courier New', 'Courier New.ttf')) registerFont(TTFont('Courier New Bold', 'Courier New Bold.ttf')) registerFont(TTFont('Courier New Italic', 'Courier New Italic.ttf')) registerFont(TTFont('Courier New Bold Italic', 'Courier New Bold Italic.ttf')) registerFontFamily('Courier New', normal='Courier New', bold='Courier New Bold', italic='Courier New Italic', boldItalic='Courier New Bold Italic') except TTFError: registerFont(TTFont('Courier New', 'Courier_New.ttf')) registerFont(TTFont('Courier New Bold', 'Courier_New_Bold.ttf')) registerFont(TTFont('Courier New Italic', 'Courier_New_Italic.ttf')) registerFont(TTFont('Courier New Bold Italic', 'Courier_New_Bold_Italic.ttf')) registerFontFamily('Courier New', normal='Courier New', bold='Courier New Bold', italic='Courier New Italic', boldItalic='Courier New Bold Italic') font = 'Courier New Bold' font_size = 9 format_ourprice='$' + ('%3.2f' % float(str(ourprice).strip('$'))) doc_width = 2.4*inch doc_height = 2*inch margin = 0.1*inch column_width = doc_width - 2*margin column_height = doc_height - 2*margin ourprice_width = stringWidth('$888.88', font, font_size) tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') #breaks string at word boundary which is less than max width in pixels def truncate_by_word( booktitle, max_width=0, split_char=' ' ): title_array = [] for i in booktitle.split(split_char): title_array.append(i) if stringWidth(split_char.join(title_array), font, font_size) > max_width: title_array.pop() break return split_char.join(title_array) saleBanner=False if float(str(ourprice).strip('$')) < float(str(listprice).strip('$')): saleBanner=True doc_height = doc_height + font_size*1.5 column_height = doc_height -2*margin canvas1 = canvas.Canvas(tmpfile, (doc_width, doc_height)) #change coordinates so origin is now at left bottom margin corner canvas1.translate(margin, margin) canvas1.saveState() text_object = canvas1.beginText() text_object.setTextOrigin(0, column_height-margin) if saleBanner==True: text_object.setFont(font, font_size+2) text_object.textLine("SALE! SALE! SALE! SALE!") text_object.setFont(font, font_size) text_object.textOut( truncate_by_word(booktitle, max_width=(column_width - ourprice_width - margin))) text_object.moveCursor(column_width - ourprice_width, 0) text_object.textLine(str(format_ourprice)) #move cursor permanently moves margin, so we have to move back to zero text_object.setXPos( -text_object.getX()) text_object.textLine(truncate_by_word(author, max_width=column_width, split_char=',')) canvas1.drawText(text_object) price_string='59999' if 0 <= float(str(ourprice).strip('$')) < 100: price_string='5' + ('%3.2f' % float(str(ourprice).strip('$'))).replace('.', '').zfill(4)[-4:] #create barcode and draw it at the origin. barcode1=barcode.createBarcodeDrawing('EAN13EXT5', value=str(isbn + price_string), validate=True, width= column_width, height=1.4*inch, humanReadable=True, fontName=font) renderPDF.draw(barcode1, canvas1, 0, 0) canvas1.restoreState() canvas1.showPage() canvas1.save() #print_command_string = string.Template(u"export TMPDIR=$tmpdir; $gs_location -q -dSAFER -dNOPAUSE -sDEVICE=pdfwrite -sourprice='$ourourprice' -sisbnstring='$isbn' -sbooktitle='$booktitle' -sauthorstring='$authorstring' -sOutputFile=%pipe%'lpr -P $printer -# $num_copies -o media=Custom.175x144' barcode_label.ps 1>&2") print(tmpfile.name) tmpfile.close() print_command_string = string.Template("lpr -P $printer -# $num_copies -o orientation-requested=3 -o media=60x60 $filename") #print_command_string = string.Template(u"open $filename") pcs_sub = print_command_string.substitute({'filename':tmpfile.name, 'printer': configuration.get('label_printer_name'), 'num_copies':num_copies}) result=subprocess.call( ' '.join(pcs_sub.split()), shell=True) print(pcs_sub, file=sys.stderr)
def __init__(self, codeName="Code128", value="", **kw): self.vertical = kw.get('vertical', 0) self.widget = createBarcodeDrawing(codeName, value=value, **kw)
def __init__(self, width=1000, height=400, *args, **kwargs): Drawing.__init__(self, width, height, *args, **kwargs) # background color self.background = Rect(0, 0, self.width, self.height, strokeWidth=0, fillColor=colors.lightgrey) # end here self.add(Circle(500, 200, 180), name='circle_perfect') self.add(Circle(500, 200, 145), name='circle_good') self.add(Circle(500, 200, 115), name='circle_medium') self.add(Circle(500, 200, 85), name='circle_bad') self.add(Circle(500, 200, 50), name='circle_awful') self.add(Circle(500, 200, 20), name='circle_center') self.add(SpiderChart(), name='background_chart') self.add(SpiderChart(), name='chart') # QR code qrw = QrCodeWidget('Well met') # QR size qrw.barHeight = 150 qrw.barWidth = 150 # QR position qrw.y = 100 qrw.x = 10 self.add(qrw) # end here # barcode barcode_group = Group() barcode = createBarcodeDrawing('EAN13', value='1234567890', width=200, height=100) barcode_group.add(barcode) barcode_group.shift(10, 10) # barcode position self.add(barcode_group) # end here self.add(String(470, 386, 'Аналіз крові'), name='text0') self.add(String(605, 352, 'Антропометрія'), name='text1') self.add(String(670, 275, 'Постава'), name='text2') self.add(String(685, 170, 'Композиція тіла'), name='text3') self.add(String(645, 75, 'Електрокардіограмма'), name='text4') self.add(String(550, 10, 'Варіаційна пульсометрія'), name='text5') self.add(String(350, 10, 'Система дихання'), name='text6') self.add(String(220, 75, 'Кистьова динамометрія'), name='text7') self.add(String(225, 170, 'Основний обмін'), name='text8') self.add(String(160, 275, 'Карідореспіраторний профіль'), name='text9') self.add(String(330, 350, 'Психотест'), name='text10') # info self.add(String(840, 366, 'Чудово'), name='info_perfect') self.circle_perfect.fillColor = colors.Color(0, 0, 255, alpha=0.3) self.circle_perfect.strokeColor = colors.transparent self.info_perfect.fontName = 'HelveticaNeueC' self.info_perfect.fontSize = 12 self.add(Rect(800, 356, 30, 30), name='rect_perfect') self.rect_perfect.fillColor = colors.Color(0, 0, 255, alpha=0.3) self.rect_perfect.strokeColor = colors.transparent self.add(String(840, 326, 'Добре'), name='info_good') self.circle_good.fillColor = colors.Color(0, 255, 0, alpha=0.5) self.circle_good.strokeColor = colors.transparent self.info_good.fontName = 'HelveticaNeueC' self.info_good.fontSize = 12 self.add(Rect(800, 316, 30, 30), name='rect_good') self.rect_good.fillColor = colors.Color(0, 255, 0, alpha=0.5) self.rect_good.strokeColor = colors.transparent self.add(String(840, 286, 'Задовільно'), name='info_medium') self.circle_medium.fillColor = colors.yellow self.circle_medium.strokeColor = colors.transparent self.info_medium.fontName = 'HelveticaNeueC' self.info_medium.fontSize = 12 self.add(Rect(800, 276, 30, 30), name='rect_medium') self.rect_medium.fillColor = colors.yellow self.rect_medium.strokeColor = colors.transparent self.add(String(840, 246, 'Погано'), name='info_bad') self.circle_bad.fillColor = colors.orange self.circle_bad.strokeColor = colors.transparent self.info_bad.fontName = 'HelveticaNeueC' self.info_bad.fontSize = 12 self.add(Rect(800, 236, 30, 30), name='rect_bad') self.rect_bad.fillColor = colors.orange self.rect_bad.strokeColor = colors.transparent self.add(String(840, 206, 'Дуже погано'), name='info_awful') self.circle_awful.fillColor = colors.red self.circle_awful.strokeColor = colors.transparent self.info_awful.fontName = 'HelveticaNeueC' self.info_awful.fontSize = 12 self.add(Rect(800, 196, 30, 30), name='rect_awful') self.rect_awful.fillColor = colors.red self.rect_awful.strokeColor = colors.transparent # end here self.chart.x = 20 self.chart.y = 40 self.chart.width = self.width - 40 self.chart.height = self.height - 80 self.background_chart.x = 10 self.background_chart.y = 20 self.background_chart.width = self.width - 20 self.background_chart.height = self.height - 40 # ruin has com to my code TODO rework this garbage self.text0.fontName = 'HelveticaNeueC' self.text0.fontSize = 12 self.text1.fontName = 'HelveticaNeueC' self.text1.fontSize = 12 self.text2.fontName = 'HelveticaNeueC' self.text2.fontSize = 12 self.text3.fontName = 'HelveticaNeueC' self.text3.fontSize = 12 self.text4.fontName = 'HelveticaNeueC' self.text4.fontSize = 12 self.text5.fontName = 'HelveticaNeueC' self.text5.fontSize = 12 self.text6.fontName = 'HelveticaNeueC' self.text6.fontSize = 12 self.text7.fontName = 'HelveticaNeueC' self.text7.fontSize = 12 self.text8.fontName = 'HelveticaNeueC' self.text8.fontSize = 12 self.text9.fontName = 'HelveticaNeueC' self.text9.fontSize = 12 self.text10.fontName = 'HelveticaNeueC' self.text10.fontSize = 12 # end here aaaaaaaaaaaaaaaaaa self.chart.labels = [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ] self.background_chart.labels = [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ] self.chart.data = [ [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], # style [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], # style [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], # style [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], # style [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # style [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # values ] self.background_chart.data = [ [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], # style [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], # style [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], # style [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], # style [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # style ] # style self.chart.strands.strokeColor = colors.transparent self.background_chart.strands.strokeColor = colors.transparent self.background_chart.spokes.strokeColor = colors.lightgrey # self.chart.strands[1].strokeWidth = 15 # self.chart.strands[1].strokeColor = colors.lightgreen # self.chart.strands[2].strokeWidth = 15 # self.chart.strands[2].strokeColor = colors.yellow # self.chart.strands[3].strokeWidth = 15 # self.chart.strands[3].strokeColor = colors.orange # self.chart.strands[4].strokeWidth = 15 # self.chart.strands[4].strokeColor = colors.red # self.background_chart.strands[0].fillColor = colors.Color(0, 0, 255, alpha=0.3) # self.background_chart.strands[1].fillColor = colors.Color(0, 255, 0, alpha=0.5) # self.background_chart.strands[2].fillColor = colors.yellow # self.background_chart.strands[3].fillColor = colors.orange # self.background_chart.strands[4].fillColor = colors.red # self.chart.strands[0].strokeColor = colors.blue # self.chart.strands[0].strokeDashArray = (4, 4) # self.chart.strands[0].symbol = makeMarker("Circle") # self.chart.strands[0].strokeWidth = 0.5 # self.chart.strands[0].symbol.fillColor = colors.black #end here self.chart.strandLabels.format = 'values' # main graph style self.chart.strands[5].strokeColor = colors.darkblue self.chart.spokes.strokeColor = colors.transparent self.chart.strands[5].symbol = makeMarker('FilledCircle', size=11) # self.chart.strandLabels.dR = -20 self.chart.strands[5].symbol.fillColor = colors.white self.chart.strands[5].strokeWidth = 2
def draw(self): canvas = self.canv canvas.setLineWidth(0.1) # logo logo = ImageReader(self.shipping_label.logo) canvas.drawImage( logo, self.x1 + 5 * mm, self.y2 - (27 * mm), width=25 * mm, preserveAspectRatio=True, anchor="sw", mask="auto", ) # datagrid datagrid = createBarcodeDrawing( "ECC200DataMatrix", value=self.shipping_label.get_datamatrix_info(), width=25 * mm, height=25 * mm) datagrid.drawOn(canvas, self.x1 + 40 * mm, self.y2 - (27 * mm)) # symbol symbol = ImageReader(self.shipping_label.symbol) canvas.drawImage( symbol, self.x1 + 70 * mm, self.y2 - (27 * mm), width=25 * mm, preserveAspectRatio=True, anchor="sw", mask="auto", ) # header shipping_labels text = Paragraph( "{}<br/>{}".format(self.shipping_label.get_invoice(), self.shipping_label.get_order()), style=self.label_style, ) text.wrap(25 * mm, 14) text.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (28 * mm) - 14) text = Paragraph( "{}<br/>{}".format(self.shipping_label.get_contract_number(), self.shipping_label.get_service_name()), style=self.label_style, ) text.wrap(25 * mm, 14) text.drawOn(canvas, self.x1 + 40 * mm, self.y2 - (28 * mm) - 14) text = Paragraph( "{}<br/>{}".format(self.shipping_label.get_package_sequence(), self.shipping_label.get_weight()), style=self.label_style, ) text.wrap(25 * mm, 14) text.drawOn(canvas, self.x1 + 70 * mm, self.y2 - (28 * mm) - 14) # tracking canvas.setFont("Helvetica-Bold", 10) canvas.drawCentredString(self.x1 + 42.5 * mm, self.y2 - 40 * mm, self.shipping_label.get_tracking_code()) code = createBarcodeDrawing("Code128", value=str( self.shipping_label.tracking_code), width=75 * mm, height=18 * mm, quiet=0) code.drawOn(canvas, 10 * mm, self.y2 - (59 * mm)) # extra services (first three) first_row = self.y2 - (40 * mm) - 10 # font-size=10pt for extra_service in self.shipping_label.extra_services: if not extra_service.display_on_label: continue canvas.drawString(self.x2 - (10 * mm), first_row, extra_service.code) first_row -= 14 # receipt receipt_style = ParagraphStyle(name="label", fontName="Helvetica", fontSize=8, leading=14) text = Paragraph(self.shipping_label.receipt_template, style=receipt_style) text.wrap(self.width - (10 * mm), 28) text.drawOn(canvas, self.x1 + (5 * mm), self.y2 - (60 * mm) - 28) # sender header canvas.setFillColor(colors.black) canvas.line(self.x1, self.y2 - (70 * mm), self.x2, self.y2 - (70 * mm)) width = stringWidth(self.shipping_label.sender_header, "Helvetica", 10) + 2 canvas.rect(self.x1, self.y2 - (70 * mm) - 14, width, 14, fill=True) canvas.setFont("Helvetica", 9) canvas.setFillColor(colors.white) canvas.drawString(self.x1 + 4, self.y2 - (70 * mm) - 10, self.shipping_label.sender_header) carrier_logo = ImageReader(self.shipping_label.carrier_logo) canvas.drawImage( carrier_logo, self.x2 - 20 * mm, self.y2 - (70 * mm) - 12, height=10, preserveAspectRatio=True, anchor="sw", mask="auto", ) # receiver receiver_style = ParagraphStyle("receiver", fontName="Helvetica", fontSize=10, leading=15) text = Paragraph(self.shipping_label.get_receiver_data(), style=receiver_style) text.wrap(self.width - 5 * mm, 24 * mm) text.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (98 * mm)) # receiver zip barcode code = createBarcodeDrawing("Code128", value=str( self.shipping_label.receiver.zip_code), width=30 * mm, height=18 * mm, quiet=0) code.drawOn(canvas, self.x1 + 5 * mm, self.y2 - (117 * mm)) # text text_style = ParagraphStyle("text", fontName="Helvetica", fontSize=10) text = Paragraph(self.shipping_label.text, style=text_style) width = self.x2 - (self.x1 + (45 * mm)) text.wrap(width, 15 * mm) text.breakLines(width) text.drawOn(canvas, self.x1 + (45 * mm), self.y2 - (98 * mm)) # sender canvas.line(self.x1, self.y2 - (118 * mm), self.x2, self.y2 - (118 * mm)) sender_style = ParagraphStyle("sender", fontName="Helvetica", fontSize=9) text = Paragraph(self.shipping_label.get_sender_data(), style=sender_style) text.wrap(self.width - 5 * mm, 22 * mm) text.drawOn(canvas, self.x1 + 5 * mm, self.y1 + 2 * mm) # border canvas.rect(self.x1, self.y1, self.width, self.height)
def print_machines_barcodes(): global header_text global sub_header_text s = ParagraphStyle(name="zou", fontName='Helvetica', fontSize=14, alignment=TA_CENTER) title_style = ParagraphStyle(name="regular", fontName='Helvetica', fontSize=24, spaceBefore=34, spaceAfter=34) zone_style = ParagraphStyle(name="zone-style", fontName='Helvetica-Bold', fontSize=24, spaceBefore=34, spaceAfter=34) badges_per_line = 3 smachines = sort_machines(machine_service.all_machines()) # I need an instance to call barcode identifier barcode_machine = Machine() if len(smachines) == 0: return complete_document = [] for clock_zone in sorted(smachines.keys()): complete_document.append( Paragraph(u">>> {}".format(clock_zone or _("Without zone")), zone_style)) machines = smachines[clock_zone] if not machines: continue for operation_name, machines in machines.items(): array = [] row = [] i = 0 for machine in machines: barcode_machine.resource_id = machine.resource_id bc = createBarcodeDrawing( 'EAN13', value=str(BarCodeIdentifier.code_for(barcode_machine)), width=5.5 * cm, barHeight=1.5 * cm) row.append([ Paragraph(u"{}".format(machine.fullname), s), platypus.Spacer(0, 0.25 * cm), bc ]) i = i + 1 if i == badges_per_line: array.append(row) row = [] i = 0 # Handle the last non complete row if i > 0: array.append(row) t = platypus.Table(array, repeatRows=0, colWidths=[6.5 * cm] * badges_per_line, rowHeights=[3 * cm] * len(array)) ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8)]) ts.add('ALIGN', (0, 0), (-1, -1), 'CENTER') ts.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ts.add("LEFTPADDING", (0, 0), (-1, -1), 0) ts.add("RIGHTPADDING", (0, 0), (-1, -1), 0) ts.add('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black) ts.add('BOX', (0, 0), (-1, -1), 0.25, colors.black) t.setStyle(ts) complete_document.append( KeepTogether([Paragraph(operation_name, title_style), t])) # complete_document.append( Paragraph(_("Operation {}").format(opid), title_style)) # complete_document.append(t) complete_document.append(PageBreak()) filename = make_pdf_filename("MachineBarcodes_") ladderDoc = basic_PDF(filename) ladderDoc.title = "" ladderDoc.subject = _(u"Machines bar codes") ladderDoc.build(complete_document, canvasmaker=NumberedCanvas) open_pdf(filename)
def __init__(self, data, barHeight=10, barWidth=10,*args, **kw): barcode = createBarcodeDrawing('Code128', value=data, barHeight=barHeight*mm, barWidth = barWidth*mm,humanReadable=True) Drawing.__init__(self,barcode.width,barcode.height,*args,**kw) self.add(barcode, name='barcode')
def barcode(self, barcode_type, value, **kwargs): defaults = { 'width': (600, int), 'height': (100, int), 'humanreadable': (False, lambda x: bool(int(x))), 'quiet': (True, lambda x: bool(int(x))), 'mask': (None, lambda x: x), 'barBorder': (4, int), # The QR code can have different layouts depending on the Error Correction Level # See: https://en.wikipedia.org/wiki/QR_code#Error_correction # Level 'L' – up to 7% damage (default) # Level 'M' – up to 15% damage (i.e. required by l10n_ch QR bill) # Level 'Q' – up to 25% damage # Level 'H' – up to 30% damage 'barLevel': ('L', lambda x: x in ('L', 'M', 'Q', 'H') and x or 'L'), } kwargs = { k: validator(kwargs.get(k, v)) for k, (v, validator) in defaults.items() } kwargs['humanReadable'] = kwargs.pop('humanreadable') if barcode_type == 'UPCA' and len(value) in (11, 12, 13): barcode_type = 'EAN13' if len(value) in (11, 12): value = '0%s' % value elif barcode_type == 'auto': symbology_guess = {8: 'EAN8', 13: 'EAN13'} barcode_type = symbology_guess.get(len(value), 'Code128') elif barcode_type == 'DataMatrix' and not self.datamatrix_available(): # fallback to avoid stacktrack because reportlab won't recognize the type and error message isn't useful/will be blocking barcode_type = 'Code128' elif barcode_type == 'QR': # for `QR` type, `quiet` is not supported. And is simply ignored. # But we can use `barBorder` to get a similar behaviour. if kwargs['quiet']: kwargs['barBorder'] = 0 try: barcode = createBarcodeDrawing(barcode_type, value=value, format='png', **kwargs) # If a mask is asked and it is available, call its function to # post-process the generated QR-code image if kwargs['mask']: available_masks = self.get_available_barcode_masks() mask_to_apply = available_masks.get(kwargs['mask']) if mask_to_apply: mask_to_apply(kwargs['width'], kwargs['height'], barcode) return barcode.asString('png') except (ValueError, AttributeError): if barcode_type == 'Code128': raise ValueError("Cannot convert into barcode.") elif barcode_type == 'QR': raise ValueError("Cannot convert into QR code.") else: return self.barcode('Code128', value, **kwargs)
tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") # generate a canvas (A4 in this case, size doesn"t really matter) canvas1 = canvas.Canvas(tmpfile, (2.4 * inch, 2 * inch)) canvas1.saveState() # create a barcode object # (is not displayed yet) # barHeight encodes how high the bars will be # barWidth encodes how wide the "narrowest" barcode unit is ean5 = "51234" barcode1 = barcode.createBarcodeDrawing( "EAN5", value=str(ean5), validate=True, width=2.4 * inch, height=1.4 * inch, humanReadable=True, fontName="Helvetica", ) renderPDF.draw(barcode1, canvas1, 0, 0) canvas1.restoreState() canvas1.showPage() canvas1.save() tmpfile.close() # print_command_string = string.Template("lpr -P $printer -# $num_copies -o media=Custom.175x120 $filename") # pcs_sub = print_command_string.substitute({'filename':tmpfile.name, 'printer': configuration.get('label_printer_name'), 'num_copies':1}) # result=subprocess.call( ' '.join(pcs_sub.split()), shell=True) # tmpfile.unlink(tmpfile.name)
def action_cfdi_generate(self): # after validate, send invoice data to external system via http post for invoice in self: if invoice.fecha_factura == False: invoice.fecha_factura = datetime.datetime.now() invoice.write({'fecha_factura': invoice.fecha_factura}) if invoice.estado_factura == 'factura_correcta': if invoice.folio_fiscal: invoice.write({'factura_cfdi': True}) return True else: raise UserError(_('Error para timbrar factura, Factura ya generada.')) if invoice.estado_factura == 'factura_cancelada': raise UserError(_('Error para timbrar factura, Factura ya generada y cancelada.')) values = invoice.to_json() pacs = self.env.user.company_id.pac_config if len(pacs) > 0: pac=pacs[0] result = pac.timbrar_xml(values) if result['validate']: xml_signed = "" if 'xml' in result: xml_signed = base64.b64decode(result['xml']) else: raise Warning("No se recibio el elemento 'xml' o 'xml_base64'") xml_obj = ET2.fromstring(xml_signed) _logger.warning(xml_signed) _logger.warning(xml_obj) xml_name = "factura_%s.xml" % invoice.name.replace(' ', '_') TFD = xml_obj.find('cfdi:Complemento', NSMAP).find('tfd:TimbreFiscalDigital', NSMAP) UUID = result['uuid'] or TFD.attrib['UUID'] fecha_timbrado = TFD.attrib['FechaTimbrado'] certificado_emisor = xml_obj.attrib['NoCertificado'] certificado_sat = TFD.attrib['NoCertificadoSAT'] lugar_expedicion = xml_obj.attrib['LugarExpedicion'] sello_digital = xml_obj.attrib['Sello'] sello_digital_sat = TFD.attrib['SelloSAT'] url = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx' qr_value = '%s?id=%s&re=%s&rr=%s&tt=%s&fe=%s' % ( url, UUID, invoice.company_id.vat, invoice.partner_id.vat, invoice.amount_total,sello_digital[-8:]) options = {'width': 275 * mm, 'height': 275 * mm} ret_val = createBarcodeDrawing('QR', value=qr_value, **options) qrcode = base64.encodestring(ret_val.asString('jpg')) xslt_file = os.path.dirname(os.path.realpath(__file__)).replace('models','data_sat/cadenaoriginal_TFD_1_1.xslt') xslt = ET2.parse(xslt_file) transform = ET2.XSLT(xslt) cad_org_tfd = '%s' % transform(TFD) vals = { 'usuario_timbrado': self.env.user.id, #'cdfi_invoice_name': xml_name, 'folio_fiscal': UUID, 'fecha_timbrado': fecha_timbrado, 'certificado_emisor': certificado_emisor, 'cetificaso_sat': certificado_sat, 'rfc_emisor': self.env.user.company_id.vat, 'lugar_expedicion': lugar_expedicion, 'selo_digital_cdfi': sello_digital, 'selo_sat': sello_digital_sat, 'qrcode_image': qrcode, 'cad_org_tfd': cad_org_tfd, 'factura_cfdi': True, 'estado_factura': 'factura_correcta' } _logger.warning(vals) pac.write({'timbres': pac.timbres + 1}) invoice.write(vals) _logger.warning("Vals guardados") xml_binary = self.env['ir.attachment'].sudo().create({ 'name': xml_name, 'datas': result['xml'], 'res_model': self._name, 'res_id': invoice.id, 'type': 'binary' }) invoice.cfdi_xml = xml_binary else: result['description'] = result.get('description', False) or '' description = result['description'] if result['description'] else "" error = "%s: %s\n" % (result['code'], description) raise Warning("%s\n%s" % (error, values)) return True
def import_xml_file_button_cargar(self): self.ensure_one() invoice_id = self.env['account.move'].browse( self._context.get('active_id')) if not self.import_file: raise Warning("Seleccione primero el archivo.") p, ext = os.path.splitext(self.file_name) if ext[1:].lower() != 'xml': raise Warning( _("Formato no soportado \"{}\", importa solo archivos XML"). format(self.file_name)) NSMAP = { 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'cfdi': 'http://www.sat.gob.mx/cfd/3', 'tfd': 'http://www.sat.gob.mx/TimbreFiscalDigital', } file_content = base64.b64decode(self.import_file) xml_data = etree.fromstring(file_content) Emisor = xml_data.find('cfdi:Emisor', NSMAP) Receptor = xml_data.find('cfdi:Receptor', NSMAP) RegimenFiscal = Emisor.find('cfdi:RegimenFiscal', NSMAP) Complemento = xml_data.find('cfdi:Complemento', NSMAP) TimbreFiscalDigital = Complemento.find('tfd:TimbreFiscalDigital', NSMAP) #xml_file_link = invoice_id.company_id.factura_dir + '/' + invoice_id.number.replace('/', '_') + '.xml' amount_str = str(xml_data.attrib['Total']).split('.') qr_value = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?&id=%s&re=%s&rr=%s&tt=%s.%s&fe=%s' % ( TimbreFiscalDigital.attrib['UUID'], invoice_id.company_id.vat, invoice_id.partner_id.vat, amount_str[0].zfill(10), len(amount_str) == 2 and amount_str[1].ljust(6, '0') or '000000', str(TimbreFiscalDigital.attrib['SelloCFD'])[-8:], ) options = {'width': 275 * mm, 'height': 275 * mm} ret_val = createBarcodeDrawing('QR', value=qr_value, **options) qrcode_image = base64.encodestring(ret_val.asString('jpg')) cargar_values = { 'methodo_pago': xml_data.attrib['MetodoPago'], 'forma_pago': xml_data.attrib['FormaPago'], 'uso_cfdi': Receptor.attrib['UsoCFDI'], 'folio_fiscal': TimbreFiscalDigital.attrib['UUID'], 'tipo_comprobante': xml_data.attrib['TipoDeComprobante'], 'fecha_factura': TimbreFiscalDigital.attrib['FechaTimbrado'] and parse(TimbreFiscalDigital.attrib['FechaTimbrado']).strftime( DEFAULT_SERVER_DATETIME_FORMAT) or False, # 'xml_invoice_link': xml_file_link, 'factura_cfdi': True, 'estado_factura': 'factura_correcta', 'numero_cetificado': xml_data.attrib['NoCertificado'], 'cetificaso_sat': TimbreFiscalDigital.attrib['NoCertificadoSAT'], 'fecha_certificacion': TimbreFiscalDigital.attrib['FechaTimbrado'], 'selo_digital_cdfi': TimbreFiscalDigital.attrib['SelloCFD'], 'selo_sat': TimbreFiscalDigital.attrib['SelloSAT'], 'tipocambio': xml_data.find('TipoCambio') and xml_data.attrib['TipoCambio'] or '1', 'moneda': xml_data.attrib['Moneda'], 'number_folio': xml_data.find('Folio') and xml_data.attrib['Folio'] or ' ', 'cadena_origenal': '||%s|%s|%s|%s|%s||' % (TimbreFiscalDigital.attrib['Version'], TimbreFiscalDigital.attrib['UUID'], TimbreFiscalDigital.attrib['FechaTimbrado'], TimbreFiscalDigital.attrib['SelloCFD'], TimbreFiscalDigital.attrib['NoCertificadoSAT']), 'qrcode_image': qrcode_image } invoice_id.write(cargar_values) #xml_file = open(xml_file_link, 'w') #xml_invoice = base64.b64decode(self.import_file) #xml_file.write(xml_invoice.decode("utf-8")) #xml_file.close() return True
def import_xml_nomina_button(self): self.ensure_one() nomina_id = self.env['hr.payslip'].browse( self._context.get('active_id')) if not self.import_file: raise Warning("Seleccione primero el archivo.") p, ext = os.path.splitext(self.file_name) if ext[1:].lower() != 'xml': raise Warning( _("Formato no soportado \"{}\", importa solo archivos XML"). format(self.file_name)) file_coontent = base64.b64decode(self.import_file) file_coontent = file_coontent.replace(b'cfdi:', b'') file_coontent = file_coontent.replace(b'tfd:', b'') try: data = json.dumps(xmltodict.parse( file_coontent)) #force_list=('Concepto','Traslado',) data = json.loads(data) except Exception as e: data = {} raise Warning(str(e)) timbrado_data = data.get('Comprobante', {}).get('Complemento', {}).get('TimbreFiscalDigital', {}) receptor_data = data.get('Comprobante', {}).get('Receptor', {}) xml_file_link = nomina_id.company_id.factura_dir + '/' + nomina_id.number.replace( '/', '_') + '.xml' amount_str = str(data.get('Comprobante', {}).get('@Total', {})).split('.') qr_value = 'https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx?&id=%s&re=%s&rr=%s&tt=%s.%s&fe=%s' % ( timbrado_data.get('@UUID'), nomina_id.company_id.rfc, nomina_id.employee_id.rfc, amount_str[0].zfill(10), amount_str[1].ljust(6, '0'), timbrado_data.get('@SelloCFD', {})[-8:], ) options = {'width': 275 * mm, 'height': 275 * mm} ret_val = createBarcodeDrawing('QR', value=qr_value, **options) qrcode_image = base64.encodestring(ret_val.asString('jpg')) cargar_values = { # 'methodo_pago': data.get('Comprobante',{}).get('@MetodoPago',{}), # 'forma_pago' : data.get('Comprobante',{}).get('@FormaPago',{}), # 'uso_cfdi': receptor_data.get('@UsoCFDI'), 'folio_fiscal': timbrado_data.get('@UUID'), # 'tipo_comprobante': data.get('Comprobante',{}).get('@TipoDeComprobante',{}), 'fecha_factura': timbrado_data.get('@FechaTimbrado') and parse(timbrado_data.get('@FechaTimbrado')).strftime( DEFAULT_SERVER_DATETIME_FORMAT) or False, 'xml_nomina_link': xml_file_link, 'nomina_cfdi': True, 'estado_factura': 'factura_correcta', 'numero_cetificado': data.get('Comprobante', {}).get('@NoCertificado', {}), 'cetificaso_sat': timbrado_data.get('@NoCertificadoSAT', {}), 'fecha_certificacion': timbrado_data.get('@FechaTimbrado', {}), 'selo_digital_cdfi': timbrado_data.get('@SelloCFD', {}), 'selo_sat': timbrado_data.get('@SelloSAT', {}), 'tipocambio': data.get('Comprobante', {}).get('@TipoCambio', {}), 'moneda': data.get('Comprobante', {}).get('@Moneda', {}), 'number_folio': data.get('Comprobante', {}).get('@Folio', {}), 'cadena_origenal': '||%s|%s|%s|%s|%s||' % (timbrado_data.get('@Version', {}), timbrado_data.get( '@UUID', {}), timbrado_data.get( '@FechaTimbrado', {}), timbrado_data.get('@SelloCFD', {}), timbrado_data.get('@NoCertificadoSAT', {})), 'qrcode_image': qrcode_image } nomina_id.write(cargar_values) xml_file = open(xml_file_link, 'w') xml_invoice = base64.b64decode(self.import_file) xml_file.write(xml_invoice.decode("utf-8")) xml_file.close() return True
def _create_barcode(order_id): """Create and return a drawing with a barcode (Code128).""" return createBarcodeDrawing(codeName='Code128', value='@%s' % order_id)
def print_report(self): if not self.env.user.has_group( 'dynamic_barcode_labels.group_barcode_labels'): raise Warning( _("You have not enough rights to access this " "document.\n Please contact administrator to access " "this document.")) if not self.product_get_ids: raise Warning(_(""" There is no product lines to print.""")) config_rec = self.env['barcode.configuration'].search([], limit=1) if not config_rec: raise Warning( _(" Please configure barcode data from " "configuration menu")) datas = { 'ids': [x.product_id.id for x in self.product_get_ids], 'model': 'product.product', 'form': { 'label_width': config_rec.label_width or 50, 'label_height': config_rec.label_height or 50, 'margin_top': config_rec.margin_top or 1, 'margin_bottom': config_rec.margin_bottom or 1, 'margin_left': config_rec.margin_left or 1, 'margin_right': config_rec.margin_right or 1, 'dpi': config_rec.dpi or 90, 'header_spacing': config_rec.header_spacing or 1, 'barcode_height': config_rec.barcode_height or 300, 'barcode_width': config_rec.barcode_width or 1500, 'barcode_type': config_rec.barcode_type or 'EAN13', 'barcode_field': config_rec.barcode_field or '', 'display_width': config_rec.display_width, 'display_height': config_rec.display_height, 'humanreadable': config_rec.humanreadable, 'product_name': config_rec.product_name, 'product_variant': config_rec.product_variant, 'price_display': config_rec.price_display, 'lot': config_rec.lot, 'product_code': config_rec.product_code or '', 'barcode': config_rec.barcode, 'currency_position': config_rec.currency_position or 'after', 'currency': config_rec.currency and config_rec.currency.id or '', 'symbol': config_rec.currency and config_rec.currency.symbol or '', 'product_ids': [{ 'product_id': line.product_id.id, 'lot_id': line.lot_id and line.lot_id.id or False, 'lot_number': line.lot_id and line.lot_id.name or False, 'qty': line.qty, } for line in self.product_get_ids] } } browse_pro = self.env['product.product'].browse( [x.product_id.id for x in self.product_get_ids]) for product in browse_pro: barcode_value = product[config_rec.barcode_field] if not barcode_value: raise Warning( _('Please define barcode for %s!' % (product['name']))) try: barcode.createBarcodeDrawing( config_rec.barcode_type, value=barcode_value, format='png', width=int(config_rec.barcode_height), height=int(config_rec.barcode_width), humanReadable=config_rec.humanreadable or False) except: raise Warning( 'Select valid barcode type according barcode field value or check value in field!' ) self.sudo()._create_paper_format(datas['form']) return self.env.ref( 'dynamic_barcode_labels.barcodelabels').report_action([], data=datas)
def __init__(self, codeName="Code128", value="", **kw): self.widget = createBarcodeDrawing(codeName, value=value, **kw)
def report_label(request, lot_number): bluearc = request.POST.get('bluearc', None) weight = request.POST.get('weight', None) quantity = request.POST.get('quantity', None) report = get_object_or_404(Report, lot_number=lot_number) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="label.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) p.setPageSize((150 * mm, 105 * mm)) # Draw Logo/Image if not bluearc: p.setFont("Helvetica", 40) p.drawCentredString(37 * mm, 90 * mm, settings.PDF_COMPANY_NAME) p.setFont("Helvetica", 10) p.drawCentredString( 37 * mm, 85 * mm, "%s . %s . %s" % (settings.PDF_COMPANY_STREET, settings.PDF_COMPANY_LOCALITY, settings.PDF_COMPANY_ZIPCODE)) p.drawCentredString( 37 * mm, 81 * mm, "%s . Fax: %s" % (settings.PDF_COMPANY_PHONE, settings.PDF_COMPANY_FAX)) p.setFont("Helvetica", 16) p.drawCentredString(37 * mm, 75 * mm, str(settings.PDF_COMPANY_WEB)) p.line(75 * mm, 105 * mm, 75 * mm, 70 * mm) else: p.drawImage(settings.PDF_BLUEARC_LOGO, 2 * mm, -6 * mm, width=59.98 * mm, preserveAspectRatio=True) # Draw Lot number/part number p.setFont("Helvetica", 20) if not bluearc: p.drawCentredString(110 * mm, 96 * mm, "Lot # %s" % report.lot_number) barcode = createBarcodeDrawing('Code128', value=report.lot_number, barWidth=0.5 * mm, barHeight=10 * mm, humanReadable=False) barcode.drawOn(p, 84 * mm, 83 * mm) p.line(75 * mm, 82 * mm, 150 * mm, 82 * mm) p.setFont("Helvetica", 13) if report.mfg_lot_number: p.drawString(78 * mm, 77 * mm, "MFG LOT # %s" % report.mfg_lot_number) if report.heat_number: p.drawString(78 * mm, 72 * mm, "HEAT # %s" % report.heat_number) else: p.drawCentredString(110 * mm, 96 * mm, report.part_number.alternate_number) barcode = createBarcodeDrawing( 'Code128', value=report.part_number.alternate_number, barWidth=0.4 * mm, barHeight=15 * mm, humanReadable=False) barcode.drawOn(p, 84 * mm, 77 * mm) # Draw Description p.setFont("Helvetica", 16) p.line(0, 70 * mm, 150 * mm, 70 * mm) p.drawString(10, 60 * mm, report.part_number.description) p.line(0, 55 * mm, 150 * mm, 55 * mm) # Draw Part Number if not bluearc: p.setFont("Helvetica", 10) p.drawString(10, 50 * mm, "Part #") p.setFont("Helvetica", 20) p.drawString(10, 40 * mm, report.part_number.part_number) barcode = createBarcodeDrawing('Code128', value=report.part_number.part_number, barWidth=0.36 * mm, barHeight=9 * mm, humanReadable=False) barcode.drawOn(p, 0, 28 * mm) p.line(0, 25 * mm, 150 * mm, 25 * mm) else: p.setFont("Helvetica", 10) p.drawString(10, 50 * mm, "Heat #") p.setFont("Helvetica", 20) p.drawString(50, 48 * mm, report.heat_number) barcode = createBarcodeDrawing('Code128', value=report.heat_number, barWidth=0.36 * mm, barHeight=15 * mm, humanReadable=False) barcode.drawOn(p, 40, 28 * mm) p.line(0, 25 * mm, 150 * mm, 25 * mm) p.line(105 * mm, 0, 105 * mm, 25 * mm) p.setFont("Helvetica", 10) p.drawString(10, 20 * mm, "Lot #") p.setFont("Helvetica", 20) p.drawString(50, 18 * mm, report.lot_number) barcode = createBarcodeDrawing('Code128', value=report.lot_number, barWidth=0.36 * mm, barHeight=15 * mm, humanReadable=False) barcode.drawOn(p, 40, 2 * mm) p.line(0, 25 * mm, 150 * mm, 25 * mm) # Draw Box Quantity if available if report.part_number.box_quantity: p.line(105 * mm, 55 * mm, 105 * mm, 25 * mm) p.setFont("Helvetica", 10) p.drawString(110 * mm, 50 * mm, "Quantity") p.setFont("Helvetica", 25) p.drawString(110 * mm, 40 * mm, str(report.part_number.box_quantity)) barcode = createBarcodeDrawing('Code128', value=str( report.part_number.box_quantity), barWidth=0.5 * mm, barHeight=9 * mm, humanReadable=False) barcode.drawOn(p, 103 * mm, 28 * mm) # Draw Other Info if not bluearc: p.line(105 * mm, 0, 105 * mm, 25 * mm) p.setFont("Helvetica", 15) p.drawString(10, 20 * mm, "Date:") p.drawString( 40 * mm, 20 * mm, localtime(report.created_at).strftime('%Y-%m-%d %H:%M %Z')) p.line(0, 18 * mm, 105 * mm, 18 * mm) p.drawString(10, 12 * mm, "Vendor #:") p.drawString(40 * mm, 12 * mm, str(report.vendor.id)) p.line(0, 10 * mm, 105 * mm, 10 * mm) if report.origin_po: p.drawString(10, 4 * mm, "PO #:") p.drawString(40 * mm, 4 * mm, report.origin_po) elif report.origin_wo: p.drawString(10, 4 * mm, "WO #:") p.drawString(40 * mm, 4 * mm, report.origin_wo) # Draw weight if weight is not None and weight != '': p.setFont("Helvetica", 10) p.drawString(107 * mm, 21 * mm, "Weight (lbs)") p.setFont("Helvetica", 25) p.drawString(115 * mm, 13 * mm, str(weight)) if quantity is not None and quantity != '': p.setFont("Helvetica", 10) p.drawString(107 * mm, 10 * mm, "Quantity (pcs)") p.setFont("Helvetica", 25) p.drawString(115 * mm, 2 * mm, str(quantity)) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) action.send(request.user, verb="generated a label", target=report) return response
def _flowable(self, node, extra_style=None): if node.tag=='pto': return self._pto(node) if node.tag=='para': style = self.styles.para_style_get(node) if extra_style: style.__dict__.update(extra_style) result = [] for i in self._textual(node).split('\n'): result.append(platypus.Paragraph(i, style, **(utils.attr_get(node, [], {'bulletText':'str'})))) return result elif node.tag=='barCode': try: from reportlab.graphics.barcode import code128 from reportlab.graphics.barcode import code39 from reportlab.graphics.barcode import code93 from reportlab.graphics.barcode import common from reportlab.graphics.barcode import fourstate from reportlab.graphics.barcode import usps from reportlab.graphics.barcode import createBarcodeDrawing except ImportError: _logger.warning("Cannot use barcode renderers:", exc_info=True) return None args = utils.attr_get(node, [], {'ratio':'float','xdim':'unit','height':'unit','checksum':'int','quiet':'int','width':'unit','stop':'bool','bearers':'int','barWidth':'float','barHeight':'float'}) codes = { 'codabar': lambda x: common.Codabar(x, **args), 'code11': lambda x: common.Code11(x, **args), 'code128': lambda x: code128.Code128(str(x), **args), 'standard39': lambda x: code39.Standard39(str(x), **args), 'standard93': lambda x: code93.Standard93(str(x), **args), 'i2of5': lambda x: common.I2of5(x, **args), 'extended39': lambda x: code39.Extended39(str(x), **args), 'extended93': lambda x: code93.Extended93(str(x), **args), 'msi': lambda x: common.MSI(x, **args), 'fim': lambda x: usps.FIM(x, **args), 'postnet': lambda x: usps.POSTNET(x, **args), 'ean13': lambda x: createBarcodeDrawing('EAN13', value=str(x), **args), 'qrcode': lambda x: createBarcodeDrawing('QR', value=x, **args), } code = 'code128' if node.get('code'): code = node.get('code').lower() return codes[code](self._textual(node)) elif node.tag=='name': self.styles.names[ node.get('id')] = node.get('value') return None elif node.tag=='xpre': style = self.styles.para_style_get(node) return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int','frags':'int'}))) elif node.tag=='pre': style = self.styles.para_style_get(node) return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int'}))) elif node.tag=='illustration': return self._illustration(node) elif node.tag=='blockTable': return self._table(node) elif node.tag=='title': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Title'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif re.match('^h([1-9]+[0-9]*)$', (node.tag or '')): styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading'+str(node.tag[1:])] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif node.tag=='image': image_data = False if not node.get('file'): if node.get('name'): if node.get('name') in self.doc.images: _logger.debug("Image %s read ", node.get('name')) image_data = self.doc.images[node.get('name')].read() else: _logger.warning("Image %s not defined", node.get('name')) return False else: import base64 newtext = node.text if self.localcontext: newtext = utils._process_text(self, node.text or '') image_data = base64.decodestring(newtext) if not image_data: _logger.debug("No inline image data") return False image = StringIO(image_data) else: _logger.debug("Image get from file %s", node.get('file')) image = _open_image(node.get('file'), path=self.doc.path) return platypus.Image(image, mask=(250,255,250,255,250,255), **(utils.attr_get(node, ['width','height']))) elif node.tag=='spacer': if node.get('width'): width = utils.unit_get(node.get('width')) else: width = utils.unit_get('1cm') length = utils.unit_get(node.get('length')) return platypus.Spacer(width=width, height=length) elif node.tag=='section': return self.render(node) elif node.tag == 'pageNumberReset': return PageReset() elif node.tag in ('pageBreak', 'nextPage'): return platypus.PageBreak() elif node.tag=='condPageBreak': return platypus.CondPageBreak(**(utils.attr_get(node, ['height']))) elif node.tag=='setNextTemplate': return platypus.NextPageTemplate(str(node.get('name'))) elif node.tag=='nextFrame': return platypus.CondPageBreak(1000) # TODO: change the 1000 ! elif node.tag == 'setNextFrame': from reportlab.platypus.doctemplate import NextFrameFlowable return NextFrameFlowable(str(node.get('name'))) elif node.tag == 'currentFrame': from reportlab.platypus.doctemplate import CurrentFrameFlowable return CurrentFrameFlowable(str(node.get('name'))) elif node.tag == 'frameEnd': return EndFrameFlowable() elif node.tag == 'hr': width_hr=node.get('width') or '100%' color_hr=node.get('color') or 'black' thickness_hr=node.get('thickness') or 1 lineCap_hr=node.get('lineCap') or 'round' return platypus.flowables.HRFlowable(width=width_hr,color=color.get(color_hr),thickness=float(thickness_hr),lineCap=str(lineCap_hr)) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.tag,)) return None
def write_data(label, width, height, data): (num1, str1, str2, str3, str4) = get_labels_from_data(data) pad = 10 # section 1 : barcode D = Drawing(width, height) d = createBarcodeDrawing('Code128', value=num1, barHeight=0.4 * inch, humanReadable=True, quiet=False) #d = createBarcodeDrawing('I2of5', value=the_num, barHeight=10*mm, humanReadable=True) barcode_width = d.width barcode_height = d.height #d.rotate(-90) #d.translate( - barcode_height ,pad) # translate d.translate(width - barcode_width - pad / 2.0, 0) # translate #pprint(d.dumpProperties()) #D.add(d) #label.add(D) label.add(d) rect = shapes.Rect(0, pad, barcode_width + pad, barcode_height + pad) rect.fillColor = None rect.strokeColor = random.choice((colors.blue, colors.red, colors.green)) #rect.strokeWidth = d.borderStrokeWidth #label.add(rect) # section 2 : room number #the_text = "gr" + str(data['youngest_child_grade']) + " rm" + str(data['youngest_child_room']) #label.add(shapes.String(15, height-15, the_text, fontName="Judson Bold", fontSize=8, textAnchor="start")) # section2: family name # Measure the width of the name and shrink the font size until it fits. font_name = "Judson Bold" font_name = "PermanentMarker" # Measure the width of the name and shrink the font size until it fits. # try out 2 options and select the one that gives a taller font text_width_limit = width - barcode_width - pad text_height_limit = height / 2.0 s1 = fit_text_in_area(str1, font_name, text_width_limit, text_height_limit) text_width_limit = width - pad text_height_limit = height - barcode_height s2 = fit_text_in_area(str1, font_name, text_width_limit, text_height_limit) if (s1.fontSize >= s2.fontSize): s = s1 else: s = s2 s.x = pad / 2.0 s.y = height - s.fontSize + pad / 2.0 s.textAnchor = "start" label.add(s) family_name_height = get_font_height(s.fontSize, str1) family_name_width = stringWidth(str1, font_name, s.fontSize) # section3: parent names text_width_limit = width - barcode_width - 2 * pad text_height_limit = (height - family_name_height) / 2.0 font_name = "Judson Bold" s = fit_text_in_area(str2, font_name, text_width_limit, text_height_limit) s.x = pad / 2.0 s.y = height - family_name_height - s.fontSize + pad / 2.0 s.textAnchor = "start" label.add(s) parent_name_height = get_font_height(s.fontSize, str2) # section4: child's names text_width_limit = width - barcode_width - 2 * pad text_height_limit = height - family_name_height - parent_name_height font_name = "Judson Bold" s = fit_text_in_area(str3, font_name, text_width_limit, text_height_limit) s.x = pad / 2.0 s.y = height - family_name_height - parent_name_height - s.fontSize + pad / 2.0 s.textAnchor = "start" label.add(s) child_name_height = s.fontSize # section 4 : label number font_name = "Judson Bold" font_size = 5 s = shapes.String(width, height - font_size, str4, fontName=font_name, fontSize=font_size, textAnchor="end") #s.x = width #s.y = 0 #s.textAnchor = "start" #label.add(s) # section 5 : logo s = shapes.Image(0, 0, 25, 25, "logo.jpg") s.x = width - barcode_width - (barcode_width - 25) / 2.0 + 1 s.y = height - pad - 15 # enough space? if ((width - family_name_width - pad) > barcode_width): label.add(s)
from contextlib import closing from distutils.version import LooseVersion from reportlab.graphics.barcode import createBarcodeDrawing from PyPDF2 import PdfFileWriter, PdfFileReader _logger = logging.getLogger(__name__) # A lock occurs when the user wants to print a report having multiple barcode while the server is # started in threaded-mode. The reason is that reportlab has to build a cache of the T1 fonts # before rendering a barcode (done in a C extension) and this part is not thread safe. We attempt # here to init the T1 fonts cache at the start-up of Odoo so that rendering of barcode in multiple # thread does not lock the server. try: createBarcodeDrawing('Code128', value='foo', format='png', width=100, height=100, humanReadable=1).asString('png') except Exception: pass def _get_wkhtmltopdf_bin(): return find_in_path('wkhtmltopdf') # Check the presence of Wkhtmltopdf and return its version at Odoo start-up wkhtmltopdf_state = 'install' try: process = subprocess.Popen([_get_wkhtmltopdf_bin(), '--version'], stdout=subprocess.PIPE,
def fullTest(fileName="test_full.pdf"): """Creates large-ish test document with a variety of parameters""" story = [] styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] styleH2 = styles['Heading2'] story = [] story.append( Paragraph('ReportLab Barcode Test Suite - full output', styleH)) story.append(Paragraph('Generated on %s' % time.ctime(time.time()), styleN)) story.append(Paragraph('', styleN)) story.append(Paragraph('Repository information for this build:', styleN)) #see if we can figure out where it was built, if we're running in source if os.path.split(os.getcwd())[-1] == 'barcode' and os.path.isdir('.svn'): #runnning in a filesystem svn copy infoLines = os.popen('svn info').read() story.append(Preformatted(infoLines, styles["Code"])) story.append(Paragraph('About this document', styleH2)) story.append(Paragraph('History and Status', styleH2)) story.append( Paragraph( """ This is the test suite and docoumentation for the ReportLab open source barcode API, being re-released as part of the forthcoming ReportLab 2.0 release. """, styleN)) story.append( Paragraph( """ Several years ago Ty Sarna contributed a barcode module to the ReportLab community. Several of the codes were used by him in hiw work and to the best of our knowledge this was correct. These were written as flowable objects and were available in PDFs, but not in our graphics framework. However, we had no knowledge of barcodes ourselves and did not advertise or extend the package. """, styleN)) story.append( Paragraph( """ We "wrapped" the barcodes to be usable within our graphics framework; they are now available as Drawing objects which can be rendered to EPS files or bitmaps. For the last 2 years this has been available in our Diagra and Report Markup Language products. However, we did not charge separately and use was on an "as is" basis. """, styleN)) story.append( Paragraph( """ A major licensee of our technology has kindly agreed to part-fund proper productisation of this code on an open source basis in Q1 2006. This has involved addition of EAN codes as well as a proper testing program. Henceforth we intend to publicise the code more widely, gather feedback, accept contributions of code and treat it as "supported". """, styleN)) story.append( Paragraph( """ This involved making available both downloads and testing resources. This PDF document is the output of the current test suite. It contains codes you can scan (if you use a nice sharp laser printer!), and will be extended over coming weeks to include usage examples and notes on each barcode and how widely tested they are. This is being done through documentation strings in the barcode objects themselves so should always be up to date. """, styleN)) story.append(Paragraph('Usage examples', styleH2)) story.append(Paragraph(""" To be completed """, styleN)) story.append(Paragraph('The codes', styleH2)) story.append( Paragraph( """ Below we show a scannable code from each barcode, with and without human-readable text. These are magnified about 2x from the natural size done by the original author to aid inspection. This will be expanded to include several test cases per code, and to add explanations of checksums. Be aware that (a) if you enter numeric codes which are too short they may be prefixed for you (e.g. "123" for an 8-digit code becomes "00000123"), and that the scanned results and readable text will generally include extra checksums at the end. """, styleN)) codeNames = getCodeNames() from reportlab.lib.utils import flatten width = [float(x[8:]) for x in sys.argv if x.startswith('--width=')] height = [float(x[9:]) for x in sys.argv if x.startswith('--height=')] isoScale = [int(x[11:]) for x in sys.argv if x.startswith('--isoscale=')] options = {} if width: options['width'] = width[0] if height: options['height'] = height[0] if isoScale: options['isoScale'] = isoScale[0] scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')] scales = list(map(float, scales and flatten(scales) or [1])) scales = list(map(float, scales and flatten(scales) or [1])) for scale in scales: story.append(PageBreak()) story.append(Paragraph('Scale = %.1f' % scale, styleH2)) story.append(Spacer(36, 12)) for codeName in codeNames: s = [Paragraph('Code: ' + codeName, styleH2)] for hr in (0, 1): s.append(Spacer(36, 12)) dr = createBarcodeDrawing(codeName, humanReadable=hr, **options) dr.renderScale = scale s.append(dr) s.append(Spacer(36, 12)) s.append(Paragraph('Barcode should say: ' + dr._bc.value, styleN)) story.append(KeepTogether(s)) SimpleDocTemplate(fileName).build(story) print('created', fileName)
def run(): styles = getSampleStyleSheet() styleN = styles["Normal"] styleH = styles["Heading1"] story = [] # for codeNames in code story.append(Paragraph("I2of5", styleN)) story.append(I2of5(1234, barWidth=inch * 0.02, checksum=0)) story.append(Paragraph("MSI", styleN)) story.append(MSI(1234)) story.append(Paragraph("Codabar", styleN)) story.append(Codabar("A012345B", barWidth=inch * 0.02)) story.append(Paragraph("Code 11", styleN)) story.append(Code11("01234545634563")) story.append(Paragraph("Code 39", styleN)) story.append(Standard39("A012345B%R")) story.append(Paragraph("Extended Code 39", styleN)) story.append(Extended39("A012345B}")) story.append(Paragraph("Code93", styleN)) story.append(Standard93("CODE 93")) story.append(Paragraph("Extended Code93", styleN)) story.append(Extended93("L@@K! Code 93 :-)")) # , barWidth=0.005 * inch)) story.append(Paragraph("Code 128", styleN)) c = Code128("AB-12345678") # , barWidth=0.005 * inch) # print 'WIDTH =', (c.width / inch), 'barWidth =', (c.barWidth / inch) # print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch) story.append(c) story.append(Paragraph("USPS FIM", styleN)) story.append(FIM("A")) story.append(Paragraph("USPS POSTNET", styleN)) story.append(POSTNET("78247-1043")) story.append(Paragraph("USPS 4 State", styleN)) story.append(USPS_4State("01234567094987654321", "01234567891")) from reportlab.graphics.barcode import createBarcodeDrawing story.append(Paragraph("EAN13", styleN)) bcd = createBarcodeDrawing("EAN13", value="123456789012") story.append(bcd) story.append(Paragraph("EAN8", styleN)) bcd = createBarcodeDrawing("EAN8", value="1234567") story.append(bcd) story.append(Paragraph("UPCA", styleN)) bcd = createBarcodeDrawing("UPCA", value="03600029145") story.append(bcd) story.append(Paragraph("USPS_4State", styleN)) bcd = createBarcodeDrawing("USPS_4State", value="01234567094987654321", routing="01234567891") story.append(bcd) story.append(Paragraph("Label Size", styleN)) story.append(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"')) story.append(Paragraph("Label Size", styleN)) story.append(XBox((1.75) * inch, 0.5 * inch, '1/2x1-3/4"')) c = Canvas("out.pdf") f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1) f.addFromList(story, c) c.save() print "saved out.pdf"