Reportlab's Code128 Barcode as HTML Image Tag with Data URI Scheme in Python

Julian Popov picture Julian Popov · Nov 12, 2012 · Viewed 7k times · Source

I need to create an Code128 Barcodes with Python/Django which have to be embeded in HTML document.

I don't want to make any temporary (or cache) files on the disk. That's why I want to embed them as Data URI Scheme.

The result have to be something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

Can you recommend me an easy way to do this?

Now I use ReportLab to create such a barcodes and embed them in PDF files, but I don't know how to export them as Data URI Scheme. If this is the recommended way to do this.

Answer

Julian Popov picture Julian Popov · Nov 12, 2012

This is my own solution:

from base64 import b64encode
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing

def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanReadable = True):

    barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize, humanReadable = humanReadable)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')

    return drawing

def get_image():

    barcode = get_barcode(value = '01234567890', width = 600)
    data = b64encode(renderPM.drawToString(barcode, fmt = 'PNG'))
    print '<img src="data:image/png;base64,{0}">'.format(data)

And also you can get barcode rotated by 90°:

def get_barcode_rotated(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanReadable = True):

    barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize, humanReadable = humanReadable)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')

    drawing_rotated = Drawing(drawing_height, drawing_width)
    drawing_rotated.rotate(90)
    drawing_rotated.translate(0, -drawing_height)
    drawing_rotated.add(drawing, name='drawing')

    return drawing_rotated

Here is an example result:

http://pastehtml.com/view/ci7qei4k1.html