示例#1
0
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)
示例#2
0
def render(scale,
           showCodes,
           code=None,
           count="",
           value="",
           showImage=False,
           template='main.html'):
    print "render called: " + str(showCodes)
    codes = None
    bcimage = None
    if showCodes or code is None or not (code in getCodeNames()):
        codes = getCodeNames()
        action = url_for('switchcode')
    else:
        action = url_for('fixcode', code=code)
    if showImage:
        bcimage = url_for('img', code=code, scale=scale, value=value)
    return render_template(template,
                           codes=codes,
                           code=code,
                           count=count,
                           value=value,
                           scale=scale,
                           bcimage=bcimage,
                           action=action)
示例#3
0
def render(scale, showCodes, code=None, count="", value="", showImage=False, template='main.html'):
    print "render called: " + str(showCodes)
    codes = None
    bcimage = None
    if showCodes or code is None or not (code in getCodeNames()):
        codes = getCodeNames()
        action = url_for('switchcode')
    else:
        action = url_for('fixcode', code=code)
    if showImage:
        bcimage = url_for('img', code=code, scale=scale, value=value)
    return render_template(template, codes=codes, code=code, count=count, value=value,
                           scale=scale, bcimage=bcimage, action=action)
 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)
示例#5
0
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)
示例#6
0
    def pypdfml_context(self, context):
        # Get a list of available fonts from a fake canvas
        fake = canvas.Canvas("fake.pdf")
        fonts = fake.getAvailableFonts()

        barcodes = []
        for name in barcode.getCodeNames():
            sample = BARCODE_SAMPLES.get(name, BARCODE_DEFAULT)
            barcodes.append({'name': name, 'sample': sample})

        context['__pypdfml__'] = {
            'fonts': fonts,
            'barcodes': barcodes,
        }
示例#7
0
"""Module with BarCodes functions on Geraldo."""

from graphics import Graphic
from utils import memoize, get_attr_value, cm

from reportlab.graphics.barcode import getCodeNames
from reportlab.graphics.barcode.common import Codabar, Code11, I2of5, MSI
from reportlab.graphics.barcode.code128 import Code128
from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget
from reportlab.graphics.barcode.code39 import Extended39, Standard39
from reportlab.graphics.barcode.code93 import Extended93, Standard93
from reportlab.graphics.barcode.usps import FIM, POSTNET
from reportlab.graphics.barcode.usps4s import USPS_4State
from reportlab.graphics.barcode import createBarcodeDrawing

SUPPORTED_BARCODE_TYPES = getCodeNames()
BARCODE_CLASSES = {
    "Codabar": Codabar,
    "Code11": Code11,
    "Code128": Code128,
    "EAN13": Ean13BarcodeWidget,
    "EAN8": Ean8BarcodeWidget,
    "Extended39": Extended39,
    "Extended93": Extended93,
    "FIM": FIM,
    "I2of5": I2of5,
    "MSI": MSI,
    "POSTNET": POSTNET,
    "Standard39": Standard39,
    "Standard93": Standard93,
    "USPS_4State": USPS_4State,
示例#8
0
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)
示例#9
0
文件: test.py 项目: gronczo/mysite
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 = map(float,scales and flatten(scales) or [1])
    scales = 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
示例#10
0
"""Module with BarCodes functions on Geraldo."""

from graphics import Graphic
from utils import memoize, get_attr_value, cm

from reportlab.graphics.barcode import getCodeNames
from reportlab.graphics.barcode.common import Codabar, Code11, I2of5, MSI
from reportlab.graphics.barcode.code128 import Code128
from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget
from reportlab.graphics.barcode.code39 import Extended39, Standard39
from reportlab.graphics.barcode.code93 import Extended93, Standard93
from reportlab.graphics.barcode.usps import FIM, POSTNET
from reportlab.graphics.barcode.usps4s import USPS_4State
from reportlab.graphics.barcode import createBarcodeDrawing

SUPPORTED_BARCODE_TYPES = getCodeNames()
BARCODE_CLASSES = {
    'Codabar': Codabar,
    'Code11': Code11,
    'Code128': Code128,
    'EAN13': Ean13BarcodeWidget,
    'EAN8': Ean8BarcodeWidget,
    'Extended39': Extended39,
    'Extended93': Extended93,
    'FIM': FIM,
    'I2of5': I2of5,
    'MSI': MSI,
    'POSTNET': POSTNET,
    'Standard39': Standard39,
    'Standard93': Standard93,
    'USPS_4State': USPS_4State,
示例#11
0
def main():

    import argparse
    import importlib

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--code', help='String to be encoded')
    parser.add_argument('-y',
                        '--height',
                        default=2,
                        dest='y',
                        type=float,
                        help='In centimeters')
    parser.add_argument('-x',
                        '--width',
                        default=3,
                        dest='x',
                        type=float,
                        help='In centimeters')
    parser.add_argument('-e',
                        '--encoder',
                        default='Code128',
                        help='Encoder to be used. E.g. QR')
    parser.add_argument('-s', '--show_text', default=1, type=int)
    parser.add_argument('-f', '--filename', default='barcode.pdf')
    parser.add_argument('-le', '--list-encoders', default=False, dest='le')
    args = parser.parse_args()

    if args.le:
        import sys
        from reportlab.graphics import barcode
        print('\nAccepted encoders are:\n')
        sys.stdout.write('\t' + '\n\t'.join(barcode.getCodeNames()) + '\n\n')
        raise NameError, "{0} not an accepted barcode encoder".format(
            args.encoder)
        sys.exit(0)

    # import pdb; pdb.set_trace()

    # Reportlab imports
    from reportlab.graphics import barcode
    from reportlab.lib.units import cm

    # Set important variables
    if args.encoder not in barcode.getCodeNames():
        import sys
        print('\nStopping here.\nAccepted encoders are:\n')
        sys.stdout.write('\t' + '\n\t'.join(barcode.getCodeNames()) + '\n\n')
        raise NameError, "{0} not an accepted barcode encoder".format(
            args.barcode)

    # make the pdf
    pdf = SingleBarcodeCanvas(args.filename,
                              pagesize=(args.x * cm, args.y * cm)
                              # ,bottomup = 0
                              )

    #ef draw_labels(self, code, h, w, encoder, show_text=1):
    pdf.draw_labels(args.code, args.x * cm, args.y * cm, args.encoder,
                    args.show_text)
    pdf.showPage()
    pdf.save()
def main():

    import argparse
    import importlib

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--codes', default='0001')
    parser.add_argument('-f', '--filename', default='barcodes')
    parser.add_argument('-r', '--recipe', default='avery_3475')
    parser.add_argument('-e',
                        '--encoder',
                        default='Code128',
                        help='Encoder to be used. E.g. QR')
    parser.add_argument('-s', '--show_text', default=1, type=int)
    parser.add_argument('-le',
                        '--list-encoders',
                        default=False,
                        dest='le',
                        action='store_true')
    parser.add_argument('-lr',
                        '--list-recipes',
                        default=False,
                        dest='lr',
                        action='store_true')
    args = parser.parse_args()

    if args.le:
        import sys
        from reportlab.graphics import barcode
        print('\nAccepted encoders are:\n')
        sys.stdout.write('\t' + '\n\t'.join(barcode.getCodeNames()) + '\n\n')
        sys.exit(0)

    if args.lr:
        import sys
        from makebarcode.recipe_database import DATABASE as DB
        print('\nDescribed recipes are:\n')
        import sys
        sys.stdout.write('\t' + '\n\t'.join(DB.keys()) + '\n\n')
        sys.stdout.write(
            '\n\tWould you like to contribute metrics for a certain label paper?\n\tPlease do so at:\n\thttps://github.com/oneyb/reportlab-barcode-recipes'
        )
        sys.exit(0)

    # import pdb; pdb.set_trace()

    # Reportlab imports
    from reportlab.graphics import barcode
    from reportlab.lib import pagesizes

    # import recipes
    from makebarcode.recipe_database import DATABASE as DB

    # Set important variables
    if args.encoder not in barcode.getCodeNames():
        import sys
        print('\nStopping here.\nAccepted encoders are:\n')
        sys.stdout.write('\t' + '\n\t'.join(barcode.getCodeNames()) + '\n\n')
        raise NameError, "{0} not an accepted barcode encoder".format(
            args.barcode)

    recipe = DB.get(args.recipe)
    pagesize = getattr(
        pagesizes,
        recipe.pop('pagesize') if recipe.get('pagesize') is not None else 'A4')

    import re
    found_script = re.search('[\[\]*./_-]', args.codes)
    if found_script is not None:
        try:
            codes = eval(args.codes)
        except NameError:
            locals().update(recipe)
            codes = eval(args.codes)
    else:
        from warnings import warn
        warn(
            "The ID to be encoded is not python code. Assuming it's a unique string.",
            Warning)
        codes = [
            args.codes for x in range(
                recipe.get('n_labels_y') * recipe.get('n_labels_x'))
        ]

    # import pdb; pdb.set_trace

    # make the pdf
    pdf = BarcodeCanvas(args.filename, pagesize=pagesize, bottomup=0)

    pdf.draw_labels(codes, args.encoder, show_text=args.show_text, **recipe)
    pdf.showPage()
    pdf.save()