生成含多个SVG格式条形码的PDF遇导入错误,求修复方案
修复
ImportError: cannot import name 'Code128' from 'code128'并生成含SVG条形码的PDF 方案一:修复原code128库的问题
1. 安装正确的库
你大概率是装了同名的错误PyPI包,先卸载再安装正确版本:
pip uninstall -y code128 pip install python-code128
2. 修复代码的SVG兼容问题
原代码中ean.svg()返回的是SVG字符串,无法直接添加到ReportLab的Group里,需要用svglib将SVG转成ReportLab可识别的图形对象。先安装依赖:
pip install svglib
修改后的完整代码:
from code128 import Code128 import csv from reportlab.graphics.shapes import Group, Drawing from reportlab.graphics import renderPDF from reportlab.lib.pagesizes import letter from svglib.svglib import svg2rlg from io import StringIO SVG_SCALE = 10 # 读取CSV文件 with open('products.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) products = [(row['code'], row['name']) for row in reader] drawing = Drawing(width=letter[0], height=letter[1]) x, y = 50, 50 for product_code, product_name in products: # 生成SVG条形码字符串 ean = Code128(product_code) barcode_svg_str = ean.svg(scale=SVG_SCALE) # 将SVG字符串转换为ReportLab图形对象 svg_drawing = svg2rlg(StringIO(barcode_svg_str)) # 定位条形码 barcode_group = Group() barcode_group.add(svg_drawing) barcode_group.transform = (1, 0, 0, 1, x, y) drawing.add(barcode_group) # 添加居中的产品名称 barcode_width = svg_drawing.width drawing.addString(x + barcode_width / 2, y - 10, product_name, fontSize=10, textAnchor="middle") # 调整下一个条形码的位置 y += 75 if y > 750: y = 50 x += 200 # 生成PDF文件 renderPDF.drawToFile(drawing, "barcodes.pdf", "Barcode Sheet")
方案二:改用更稳定的python-barcode库
如果原库仍有问题,推荐使用python-barcode这个主流条形码生成库,API更稳定且支持多种格式:
1. 安装依赖
pip install python-barcode svglib reportlab
2. 完整代码
import csv from reportlab.graphics.shapes import Group, Drawing from reportlab.graphics import renderPDF from reportlab.lib.pagesizes import letter from svglib.svglib import svg2rlg from io import BytesIO import barcode from barcode.writer import SVGWriter # 读取CSV文件 with open('products.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) products = [(row['code'], row['name']) for row in reader] drawing = Drawing(width=letter[0], height=letter[1]) x, y = 50, 50 # 预设条形码尺寸,可按需调整 BARCODE_WIDTH = 150 BARCODE_HEIGHT = 50 for product_code, product_name in products: # 生成Code128 SVG条形码(关闭自带文本,自行添加产品名) code128 = barcode.get('code128', product_code, writer=SVGWriter()) svg_buffer = BytesIO() code128.write(svg_buffer, options={'width': BARCODE_WIDTH, 'height': BARCODE_HEIGHT, 'write_text': False}) svg_buffer.seek(0) # 转换为ReportLab图形对象 svg_drawing = svg2rlg(svg_buffer) # 定位并添加到画布 barcode_group = Group() barcode_group.add(svg_drawing) barcode_group.transform = (1, 0, 0, 1, x, y) drawing.add(barcode_group) # 添加居中的产品名称 drawing.addString(x + BARCODE_WIDTH / 2, y - 10, product_name, fontSize=10, textAnchor="middle") # 调整位置,满页后换列 y += 75 if y > 750: y = 50 x += 220 # 保存PDF文件 renderPDF.drawToFile(drawing, "barcodes.pdf", "Barcode Sheet")
内容的提问来源于stack exchange,提问作者usert4jju7
相关产品推荐
相关产品推荐

