Beispiel #1
0
def test_generate_with_file_and_writer():
    with open(os.path.join(TESTPATH, "generate_with_file_and_writer.jpeg"),
              "wb") as f:
        barcode.generate("ean13",
                         "123455559121112",
                         output=f,
                         writer=SVGWriter())
Beispiel #2
0
def barcode(event, context):
    buf = BytesIO()
    generate('EAN13', '5901234123457', writer=SVGWriter(), output=buf)
    result = buf.getvalue().decode('utf-8')
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'image/svg+xml',
        },
        'body': result,
        'isBase64Encoded': False,
    }
Beispiel #3
0
def format_inline_barcode(data):
    barcodefile = StringIO()

    # data is written into the SVG without a CDATA, so base64 encode it
    code128 = barcode.get('code128', data, writer=SVGWriter())
    code128.write(barcodefile, {'write_text': False})
    barcodefile.seek(0)

    root = etree.XML(barcodefile.read())
    # Allow us to scale it with CSS
    root.attrib['viewBox'] = '0 0 %s %s' % (root.attrib['width'], root.attrib['height'])
    del root.attrib['width']
    del root.attrib['height']
    root.attrib['preserveAspectRatio'] = 'none'

    return Markup(etree.tostring(root))
Beispiel #4
0
    def __call__(self, pg):
        code = self.text.format(pg=self.startnum + pg)
        if self.format == 'code128':
            bcode = barcode.codex.Code128(code=code, writer=SVGWriter())
            bcode_svg = bcode.render(dict(module_width=.3))
        elif self.format == 'qr':
            img_w = 50
            img = qrcode.make(
                code,
                box_size=7.5,
                image_factory=qrcode.image.svg.SvgImage,
                error_correction=qrcode.constants.ERROR_CORRECT_H)
            bcode_raw = img.get_image()
            w = float(bcode_raw.attrib['width'].replace('mm', ''))
            h = float(bcode_raw.attrib['height'].replace('mm', ''))
            img_h = h + 5
            img.save('outcode_raw.svg')
            bcode_raw.tag = 'g'
            bcode_raw.attrib['transform'] = 'translate({}mm,0)'.format(
                old_div((img_w - w), 2.))
            del bcode_raw.attrib['height']
            del bcode_raw.attrib['width']
            del bcode_raw.attrib['version']
            del bcode_raw.attrib['xmlns']

            bcode_xml = etree.Element(
                'svg', {
                    'width': "{}mm".format(img_w),
                    'height': "{}mm".format(img_h),
                    'version': "1.1",
                    'xmlns': "http://www.w3.org/2000/svg",
                })

            text_xml = etree.Element('text')
            text_xml.attrib['text-anchor'] = 'middle'
            text_xml.attrib['x'] = '{}mm'.format(
                old_div((img_w - w), 2.) + old_div(w, 2.))
            text_xml.attrib['y'] = '{}mm'.format(h + 2)
            text_xml.attrib['font-size'] = '10'
            text_xml.attrib['font-family'] = 'Verdana'
            text_xml.text = code

            bcode_xml.append(bcode_raw)
            bcode_xml.append(text_xml)
            bcode_svg = etree.tostring(bcode_xml)
        bcode_pdf = cairosvg.svg2pdf(bcode_svg)
        return bcode_pdf
Beispiel #5
0
def format_inline_barcode(data):
    barcodefile = io.BytesIO()

    # data is written into the SVG without a CDATA, so base64 encode it
    code128 = barcode.get("code128", data, writer=SVGWriter())
    code128.write(barcodefile, {"write_text": False})
    barcodefile.seek(0)

    root = etree.XML(barcodefile.read())
    # Allow us to scale it with CSS
    root.attrib["viewBox"] = "0 0 %s %s" % (root.attrib["width"],
                                            root.attrib["height"])
    del root.attrib["width"]
    del root.attrib["height"]
    root.attrib["preserveAspectRatio"] = "none"

    return Markup(etree.tostring(root).decode("utf-8"))
Beispiel #6
0
def create_barcode(args, parser):
    args.type = args.type.upper()
    if args.type != 'SVG' and args.type not in IMG_FORMATS:
        parser.error('Unknown type {type}. Try list action for available '
                     'types.'.format(type=args.type))
    args.barcode = args.barcode.lower()
    if args.barcode not in barcode.PROVIDED_BARCODES:
        parser.error('Unknown barcode {bc}. Try list action for available '
                     'barcodes.'.format(bc=args.barcode))
    if args.type != 'SVG':
        opts = dict(format=args.type)
        writer = ImageWriter()
    else:
        opts = dict(compress=args.compress)
        writer = SVGWriter()
    out = os.path.normpath(os.path.abspath(args.output))
    name = barcode.generate(args.barcode, args.code, writer, out, opts)
    print('New barcode saved as {0}.'.format(name))
Beispiel #7
0
def create_barcode(args, parser):
    args.type = args.type.upper()
    if args.type != "SVG" and args.type not in IMG_FORMATS:
        parser.error(
            "Unknown type {type}. Try list action for available types.".format(
                type=args.type))
    args.barcode = args.barcode.lower()
    if args.barcode not in barcode.PROVIDED_BARCODES:
        parser.error(
            "Unknown barcode {bc}. Try list action for available barcodes.".
            format(bc=args.barcode))
    if args.type != "SVG":
        opts = {"format": args.type}
        writer = ImageWriter()
    else:
        opts = {"compress": args.compress}
        writer = SVGWriter()
    out = os.path.normpath(os.path.abspath(args.output))
    name = barcode.generate(args.barcode, args.code, writer, out, opts,
                            args.text)
    print("New barcode saved as {}.".format(name))
Beispiel #8
0
def PrintView(request):
    allRequested = Spare.objects.filter(transNo=1)

    # from barcode import EAN13
    # from barcode.writer import ImageWriter

    # with open('static/barcode/1.png', 'wb') as f:
    #    EAN13('123456789102', writer=ImageWriter()).write(f)

    rv = BytesIO()
    code = barcode.get('code128', '10299332233', writer=SVGWriter())
    code.write(rv)

    rv.seek(0)
    # get rid of the first bit of boilerplate
    rv.readline()
    rv.readline()
    rv.readline()
    rv.readline()
    # read the svg tag into a string
    svg = rv.read()
    

    fullC = []
    for eachReq in allRequested:
        qty = eachReq.qty
        spare = eachReq.spare
        partname = eachReq.partname
        realpartname = Part.objects.get(id=partname).partname
        context = {
            'qty':qty,
            'spare':spare,
            'partname':realpartname,
        }
        fullC.append(context)
    return render(request,'printout.html',{'data':fullC,'transno':'120000200','svg':svg.decode('utf-8')})
Beispiel #9
0
            'name': args.memberName,
        },
        'membershipNumber': args.membershipNumber,
    }
    if args.programName:
        metadata['programName'] = args.programName

    # Handle barcode generation
    image = None
    if args.barcode:
        barcode_type, barcode_data = args.barcode.split(':', 1)

        fp = io.BytesIO()
        barcode.generate(barcode_type,
                         barcode_data,
                         writer=SVGWriter(),
                         output=fp)
        image = ('data:image/svg+xml;base64,%s' %
                 (base64.b64encode(fp.getvalue()).decode('utf-8')))
        fp.close()
    elif args.image:
        mime = magic.Magic(mime=True).from_file(args.image)
        with open(args.image, 'rb') as fp:
            image = 'data:%s;base64,%s' % (mime, base64.b64encode(
                fp.read()).decode('utf-8'))

    if image:
        metadata['image'] = image

    # Index token
    headers = {}
def test_saving_svg_to_byteio_with_guardbar():
    rv = BytesIO()
    EAN13(str(100000902922), writer=SVGWriter(), guardbar=True).write(rv)

    with open(f"{TESTPATH}/somefile_guardbar.svg", "wb") as f:
        EAN13("100000011111", writer=SVGWriter(), guardbar=True).write(f)
Beispiel #11
0
    def object(self, protocol_id, **kw):
        uid = SUPERUSER_ID
        cr = http.request.cr
        ir_model_data_obj = request.registry.get('ir.model.data')
        ir_model_data_id = ir_model_data_obj.search(
            cr, uid, [('name', '=', 'configurazione_default')])[0]
        ir_model_data = ir_model_data_obj.browse(cr, uid, ir_model_data_id)
        configurazione = request.registry.get(ir_model_data.model).browse(
            cr, uid, ir_model_data.res_id)

        document = http.request \
            .env["protocollo.protocollo"] \
            .search([["id", "=", protocol_id]])

        if len(document) == 0:
            return "Document not found"

        number = document.name

        dest_tz = pytz.timezone("Europe/Rome")
        date_obj = datetime.datetime.strptime(document.registration_date,
                                              "%Y-%m-%d %H:%M:%S")
        date_obj_dest = pytz.utc.localize(date_obj).astimezone(dest_tz)

        year = document.year
        type = document.type  # IN or OUT
        ammi_code = document.registry.company_id.ammi_code
        ident_code = document.aoo_id.ident_code
        registry_code = document.registry.code

        barcode_text = "%04d0%s" % (year, number)
        type_str = "Ingresso" if type == "in" else "Uscita"
        prot_str = "%04d%s" % (year, number)
        datetime_str = date_obj_dest.strftime("%Y-%m-%d %H:%M:%S")

        filename = re.sub(r"[^\w\s]", "", number)
        filename = re.sub(r"\s+", " ", filename)
        filename = "%s - %s.pdf" % (strftime("%Y-%m-%d %H-%M-%S"), filename)

        tmp_filename = os.path.join(tempfile.gettempdir(), filename)

        pos = LabelPosition()
        # pos.set_pagesize_mm(company.etichetta_larghezza, company.etichetta_altezza)
        pos.set_pagesize_mm(configurazione.etichetta_larghezza,
                            configurazione.etichetta_altezza)

        pdfdoc.PDFCatalog.OpenAction = "<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:false}\);)>>"

        pdf = canvas.Canvas(filename=tmp_filename,
                            pagesize=pos.get_pagesize_points())

        module_path = get_module_path('seedoo_protocollo_dematerializzazione')
        pdfmetrics.registerFont(
            TTFont(
                "sans",
                os.path.join(module_path, "fonts",
                             "LiberationSans-Regular.ttf")))
        pdfmetrics.registerFont(
            TTFont(
                "sans_bold",
                os.path.join(module_path, "fonts", "LiberationSans-Bold.ttf")))
        pdfmetrics.registerFont(
            TTFont(
                "monospace",
                os.path.join(module_path, "fonts",
                             "LiberationMono-Regular.ttf")))
        pdfmetrics.registerFont(
            TTFont(
                "monospace_bold",
                os.path.join(module_path, "fonts", "LiberationMono-Bold.ttf")))

        writer = SVGWriter()
        writer.set_options({
            "compress": False,
            "module_width": pos.x_mm(90),
            "module_height": pos.y_mm(60)
        })
        ean = barcode.get(name="ean13", code=barcode_text, writer=writer)

        temp_filename = "".join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(32))
        temp_image = os.path.join(tempfile.gettempdir(), temp_filename)
        svg_image = open(temp_image, "wb")
        ean.write(svg_image)
        svg_image.close()

        svg_image = open(temp_image, "rb")
        svg_lines = svg_image.readlines()
        svg_image.close()

        for i, s in enumerate(svg_lines):
            if any(
                    item in s for item in
                ["xml version", "DOCTYPE", "DTD SVG 1.1", "http://www.w3.org"
                 ]):
                svg_lines[i] = ""
            if "xmlns" in s:
                svg_lines[i] = s.replace(
                    " xmlns=\"http://www.w3.org/2000/svg\"", "")

        svgdoc = etree.fromstringlist(svg_lines)

        for bad in svgdoc.xpath(
                "//rect[@height=\"100%\" and @width=\"100%\"]"):
            bad.getparent().remove(bad)

        for bad in svgdoc.xpath("text"):
            bad.getparent().remove(bad)

        for bad in svgdoc.xpath("//rect[last()]"):
            bad.getparent().remove(bad)

        etree.strip_elements(svgdoc, etree.Comment)

        et = etree.ElementTree(svgdoc)
        svg_image = open(temp_image, "wb")
        et.write(svg_image)
        svg_image.close()

        png_image = "%s.png" % temp_image

        call([
            "inkscape", "--file", temp_image, "--export-png", png_image,
            "--export-dpi", "600", "--export-area-drawing"
        ])
        os.remove(temp_image)

        pdf.drawImage(png_image,
                      pos.x_p(5),
                      pos.y_p(0),
                      preserveAspectRatio=False,
                      width=pos.x_p(90),
                      height=pos.y_p(30))
        os.remove(png_image)

        # TODO: What to do with barcode number????
        # text_width = stringWidth(barcode_text, "monospace", 5)
        # temp_text = pdf.beginText((pos.get_pagesize_points()[0] - text_width) / 2, pos.y_p(0))
        # temp_text.setFont("monospace", 5)
        # temp_text.textOut(ean.get_fullcode())
        # pdf.drawText(temp_text)

        temp_text = pdf.beginText(pos.y_p(5), pos.y_p(85))
        temp_text.setFont("sans", 8)
        temp_text.textOut("%s - %s" % (ammi_code, ident_code))
        pdf.drawText(temp_text)

        temp_text = pdf.beginText(pos.y_p(5), pos.y_p(75))
        temp_text.setFont("sans", 8)
        temp_text.textOut(registry_code)
        pdf.drawText(temp_text)

        temp_text = pdf.beginText(pos.y_p(5), pos.y_p(65))
        temp_text.setFont("sans", 8)
        temp_text.textOut(type_str)
        pdf.drawText(temp_text)

        temp_text = pdf.beginText(pos.y_p(5), pos.y_p(45))
        temp_text.setFont("sans_bold", 8)
        temp_text.textOut("Prot. n. %s " % prot_str)
        pdf.drawText(temp_text)

        temp_text = pdf.beginText(pos.y_p(5), pos.y_p(35))
        temp_text.setFont("sans", 8)
        temp_text.textOut("del %s" % datetime_str)
        pdf.drawText(temp_text)

        company_logo_data = base64.b64decode(
            document.registry.company_id.logo_web)
        company_logo_png = Image.open(BytesIO(company_logo_data))
        company_logo = Image.new("RGB", company_logo_png.size, (255, 255, 255))
        company_logo.paste(company_logo_png, (0, 0), company_logo_png)

        company_logo_filename = os.path.join(
            tempfile.gettempdir(), "".join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(32)))
        company_logo_image = open(company_logo_filename, "wb")
        company_logo.save(company_logo_image, format="PNG")
        company_logo_image.close()

        pdf.drawImage(company_logo_filename,
                      pos.x_p(61),
                      pos.y_p(61),
                      preserveAspectRatio=True,
                      width=pos.x_p(38),
                      height=pos.y_p(38))
        os.remove(company_logo_filename)

        pdf.save()

        with file(tmp_filename) as tmpf:
            pdf_content = tmpf.read()

        os.remove(tmp_filename)

        return request.make_response(
            pdf_content,
            [("Content-Type", "application/pdf"),
             ("Content-Disposition", "inline; filename=%s" % filename)])