Add images to labels with reportlab

Viewed 15

Having a real hard time figuring this out through the documentation. I want to create labels with barcodes on them. I already have the barcodes created as images ('png'). I want to insert these images into my labels via reportlab, but cannot figure out how.

Here is my code:

import labels
from reportlab.graphics import shapes

# PAPER DIMENSIONS
PADDING = 1
specs = labels.Specification(
    215.9, 279.4, 3, 10, 64, 25.4, corner_radius=2,
    left_margin=5, right_margin=5, top_margin=13,
    left_padding=PADDING, right_padding=PADDING, top_padding=PADDING,
    bottom_padding=PADDING,
    row_gap=0)


# MAKE LABELS
def draw_label(label, width, height, obj):
    # Just convert the object to a string and print this at the bottom left of
    # the label.
    label.add(shapes.String(width / 4, height / 2, str(obj), fontName="Helvetica", fontSize=20))

# CREATE SHEET
sheet = labels.Sheet(specs, draw_label, border=True)

# THIS IS WHERE THE BARCODE IMAGES WOULD GO. CURRENTLY REPRESENTED AS TYPE STRING
sheet.add_label("Barcode 1")
sheet.add_label("Barcode 2")
sheet.add_label("Barcode 3")

# SAVE FILE
sheet.save('labels.pdf')
print("{0:d} label(s) output on {1:d} page(s).".format(sheet.label_count, sheet.page_count))
1 Answers

Ended up just creating barcodes via reportlab using that instead. Still have no idea how to insert images and fit them within specific dimensions.

Anyway, here's how to create barcodes set to the specifications of Avery 5160 labels

import labels
from reportlab.graphics import shapes
from reportlab.graphics.barcode import createBarcodeDrawing

PADDING = 1
specs = labels.Specification(
    215.9, 279.4, 3, 10, 64, 25.4, corner_radius=2,
    left_margin=5, right_margin=5, top_margin=13,
    left_padding=5.5, right_padding=PADDING, top_padding=PADDING,
    bottom_padding=9,
    row_gap=0)

def draw_label(label, width, height, obj):
    (labelstr, barcodestr) = obj
    label.add(shapes.String(width / 4, height / 2, labelstr, fontName="Helvetica", fontSize=20))
    label.add(createBarcodeDrawing('Code128', value=barcodestr, width=150, height=20))


# Create the sheet.
sheet = labels.Sheet(specs, draw_label, border=True)

# Add a couple of labels.
sheet.add_label(('label1', 'BARONE',))
sheet.add_label(('label2', 'BARTWO',))


# Save the file and we are done.
sheet.save('labels.pdf')
print("{0:d} label(s) output on {1:d} page(s).".format(sheet.label_count, sheet.page_count))
Related