我终于用其他不工作的代码片段找到了答案
from reportlab.graphics.barcode import code128
from reportlab.lib.units import mm, inch, cm, pica
from reportlab.pdfgen import canvas
code = "asdasda" #remove this if in function
c = canvas.Canvas(f"{code}.pdf")
page_width = 550 # page width
# add specific unit here as x= num*unit
# pica,mm and no unit works, I don't know why the 2 other don't
page_height = 200 # page height
# add specific unit here as x= num*unit
# pica,mm and no unit works, I don't know why the 2 other don't
margin_y = 10 # top/bottom margin
# add specific unit here as x= num*unit
# pica,mm and no unit works, I don't know why the 2 other don't
bar_height = page_height - (margin_y * 2) # barcode line height
bar_width = page_width / (11 * len(str(code)) + 55) # barcode individual width has the formula
# page width / (11*string_length) + 55 ##(I also saw +35 but in my test it was not working)
c.setPageSize((page_width, page_height)) # set page to said mesure
humanReadable = True # with or without text
barcode = code128.Code128(code,
barHeight=bar_height,
barWidth=bar_width,
humanReadable=humanReadable)
drawon_x = 0 # x value for drawing already has a margin (not like Y) bar with formula account for that
if humanReadable:
drawon_y = page_height - margin_y - bar_height # if text reduce bar height to hace the correct value
else:
drawon_y = page_height - bar_height # set draw point to the top of the page - the height of the drawn barcode
barcode.drawOn(c, drawon_x, drawon_y) # do the drawing
c.save() # save pdf
如果您想要多个单独的条形码传递这样的代码列表
def createSinglePDFBarcode(code):
#code from above here
if __name__ == "__main__":
import random
import string
num = 5
# Generate {num} random numbers between 10 and 30
# printing uppercase
letters = string.ascii_uppercase
randomSList =[] #list of code you want as barcode
for x in range(num):
randomSList.append(''.join(random.choice(letters) for i in range(10)))
for x in randomSList: # for each code make a barcode
createSinglePDFBarcode(x)