pythonpython-3.xloopspdf417

How can I create multiple barcodes at the same time using Python and pdf417


I'm looking to write a few hundred barcodes for work. I want it to be done at the same time as to not manually run a script for each barcode. The script I currently have only writes one barcode when I need 400.

from pdf417 import encode, render_image, render_svg

r1 = 0
r2 = 401

def createlist(r1, r2):
    return [item for item in range(r1, r2)]

results = ((createlist(r1, r2)))

results = [str(i) for i in results]

#print(results)


for item in results:
    #print(str(item))
    codes = encode(str(item), columns=3, security_level=2)
    image = render_image(codes, scale=5, ratio=2, padding=5, fg_color="Indigo", bg_color="#ddd")  # Pillow Image object
    image.save('barcode.jpg')

This script returns only one barcode file when I need 400 of them returned. This is python 3.7 and the latest release of Pdf417. Thank you in advance.


Solution

  • Your script is writing 400 barcodes (actually, 401 barcodes), but it does so by writing them all to the same filename, replacing the previous barcode file each time it writes a new one.

    To generate separate files, you simply need to vary the filename. For example:

    from pdf417 import encode, render_image, render_svg
    
    r1 = 0
    r2 = 401
    
    def createlist(r1, r2):
        return [item for item in range(r1, r2)]
    
    results = ((createlist(r1, r2)))
    
    results = [str(i) for i in results]
    
    #print(results)
    
    
    for item in results:
        #print(str(item))
        codes = encode(str(item), columns=3, security_level=2)
        image = render_image(codes, scale=5, ratio=2, padding=5, fg_color="Indigo", bg_color="#ddd")  # Pillow Image object
        image.save(f'barcode{item}.jpg')
    
    

    This generates barcode0.jpg through barcode400.jpg.