Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python reportlab barcode code128 size

i want to create a label (57*32mm) with a code128 barcode. Its all fine but the barcode is to small =( How can i make this barcode bigger ?

from reportlab.graphics.barcode import code128
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas

c = canvas.Canvas("test.pdf")
c.setPageSize((57*mm,32*mm))
barcode = code128.Code128("123456789")
barcode.drawOn(c, 2*mm, 20*mm)
c.showPage()
c.save()
like image 244
Steffen Avatar asked Jan 08 '23 20:01

Steffen


2 Answers

By looking up the source code for reportlab on GitHub, I found out that the barcode object has a width property. By simply using

canvas.saveState()
canvas.translate(2*cm, 3*cm) # bottom left corner of the barcode
canvas.scale(15*cm / barcode.width, 2*cm / barcode.height) # resize (15 cm and 2 cm)
barcode.drawOn(canvas, 0, 0)
canvas.restoreState()

You can obtain the obtain of the exact size you desire.

like image 137
Guillaume Proux Avatar answered Jan 18 '23 17:01

Guillaume Proux


The total width of the barcode is bar_width * total_char_widths + quiet space So.. the correct barWidth can be determined by

from reportlab.graphics.barcode import code128
final_size = 100 # arbitrary
# setting barWidth to 1
initial_width = .1

barcode128 = code128.Code128(barcode_value, humanReadable=True, barWidth=initial_width,
                             barHeight=1)
# creates the barcode, computes the total size
barcode128._calculate()
# the quiet space before and after the barcode
quiet = barcode128.lquiet + barcode128.rquiet
# total_wid = barWidth*charWid + quiet_space
# char_wid = (total_width - quiet) / bar_width
char_width = (barcode128._width - quiet) / barcode128.barWidth
# now that we have the char width we can calculate the bar width
bar_width = (final_size - quiet) / char_width
# set the new bar width
barcode128.barWidth = bar_width
# re-calculate
barcode128._calculate()

# draw the barcode on the canvas
wid, hgt = barcode128._width, barcode128._height
x_pos = y_pos = final_size # arbitrary
barcode128.drawOn(your_canvas, x_pos, y_pos)
like image 30
user2682863 Avatar answered Jan 18 '23 16:01

user2682863