Search code examples
pythonpdfbarcodereportlab

How to get the barcode width?


I need to put a barcode 128 on the bottom right of an A4 size PDF with reportlab, with a margin of 5mm.

For this we need to get the actual width of the barcode before using drawOn on the canvas.

How to get the width of a reportlab barcode, after it's created?

Note: I tried with barHeight and barWidth but the latter doesn't give the full width of the barcode, but only the smallest distance between two bars, more or less.


Solution

  • When doing:

    barcode = code128.Code128(ID, barHeight=1 * cm, barWidth=1.5, quiet=False)
    

    then simply barcode.width gives its width :)

    Indeed Code128 is a subclass of the class MultiWidthBarcode which itself is subclass of Barcode which has the property width defined here:

    def width(self):
        self._calculate()
        return self._width
    width = property(width)
    

    Then, here is how to place a barcode on bottom right corner of an A4 sheet:

    MARGIN = 0.5 * cm
    barcode.drawOn(c, 21 * cm - MARGIN - barcode.width, MARGIN)