Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
943 B
4
Indexable
def generate_custom_code128(product_code, dpi=300, paper_size=(1, 2.125)):
    barcode = code128.image(product_code, thickness=3, height=int(1.2 * dpi))
    paper_width = int(paper_size[0] * dpi)
    paper_height = int(paper_size[1] * dpi)
    image = Image.new('1', (paper_width, paper_height), 1)
    barcode = barcode.rotate(90, expand=True)
    barcode_width, barcode_height = barcode.size
    x_pos = int((paper_width - barcode_width) / 2)
    y_pos = int((paper_height - barcode_height) / 2)
    image.paste(barcode, (x_pos, y_pos))
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("arial.ttf", 10)
    text_width, text_height = draw.textsize(product_code, font=font)
    text_x = x_pos + barcode_width + 2
    text_y = int((paper_height - text_height) / 2)
    draw.text((text_x, text_y), product_code, font=font, fill=0)
    output = io.BytesIO()
    image.save(output, format="PNG")
    output.seek(0)
    return output