0

I am trying to generate a PDF containing all the barcodes in SVG format. Here is the code I've written so far.

from code128 import Code128
import csv
from reportlab.graphics.shapes import Group, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import letter

# Scale of SVG images
SVG_SCALE = 10

# Read the CSV file
with open('products.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    products = [(row['code'], row['name']) for row in reader]

# Generate barcodes for each product and add to drawing
drawing = Drawing(width=letter[0], height=letter[1])
x, y = 50, 50
for product_code, product_name in products:
    # Generate SVG barcode using code128 library
    ean = Code128(product_code)
    barcode_svg = ean.svg(scale=SVG_SCALE)

    # Create a reportlab group for the barcode and set its transform
    barcode_group = Group()
    barcode_group.transform = (SVG_SCALE, 0, 0, SVG_SCALE, x, y)
    barcode_group.add(barcode_svg)
    drawing.add(barcode_group)

    # Add product name below barcode
    drawing.addString(x + (barcode_svg.width * SVG_SCALE) / 2, y - 10, product_name, fontSize=10, textAnchor="middle")

    # Move cursor to the next barcode position
    y += 75
    if y > 750:
        y = 50
        x += 200

# Render drawing as PDF
renderPDF.drawToFile(drawing, "barcodes.pdf", "Barcode Sheet")

The error I get is ImportError: cannot import name 'Code128' from 'code128'

I can't find another way to achieve what I'm after. Can someone please help me fix the imports/code or another way of achieving this?

usert4jju7
  • 1,653
  • 3
  • 27
  • 59

1 Answers1

0

Firstly install python_barcode package. Don't get confused with barcode package. barcode package must be un-installed if already isntalled.

from barcode.codex import Code128
from barcode.writer import SVGWriter
import csv
import os

BARCODE_SCALE = 3

if not os.path.exists('gen_svg'):
    os.makedirs('gen_svg')


def generate_barcode_svg(code):
    barcode_svg = Code128(code, writer=SVGWriter())
    return barcode_svg.render()


with open('products.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        svg_name = row['code']
        product_string = row['code'] + ' : ' + row['name']
        barcode_svg = generate_barcode_svg(product_string)
        with open(f'gen_svg/{svg_name}.svg', 'w') as f:
            f.write(barcode_svg.decode('utf-8'))
usert4jju7
  • 1,653
  • 3
  • 27
  • 59