Trent Xavier
Trent Xavier

Reputation: 237

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.

Upvotes: 0

Views: 1358

Answers (2)

James O'Doherty
James O'Doherty

Reputation: 2246

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.

Upvotes: 1

Jack Thomson
Jack Thomson

Reputation: 490

Try this. I believe you weren't enumerating your barcode.jpg and were writing to the same file multiple times. You'll want to do to 400 as well to create only 400 barcodes.

from pdf417 import encode, render_image, render_svg

r1 = 0
r2 = 400

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{0}.jpg'.format(item))

Upvotes: 0

Related Questions