Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
5
Indexable
Never
from barcode import Code128
from barcode.writer import ImageWriter
from PIL import Image, ImageDraw

def generate_barcode(product_code):
    writer = ImageWriter()
    writer.dpi = 300

    barcode_image = Code128(product_code, writer=writer)
    output_filename = 'temp_barcode'
    barcode_image.save(output_filename)

    raw_image = Image.open(output_filename + ".png").convert('1')  # Convert the image to 1-bit mode
    
    dpi = 300  # Use a fixed DPI value (adjust it according to your printer's DPI)
    page_size_mm = (25.4, 54)
    page_size_pixels = tuple(int(dpi * page_size_mm[i] / 25.4) for i in (0, 1))
    desired_width = page_size_pixels[1] - 10  # Subtract a small margin
    desired_height = page_size_pixels[0] - 10  # Subtract a small margin

    # Create a new image with desired size and DPI
    final_image = Image.new('1', (desired_width, desired_height), color='white')
    final_image.info['dpi'] = (dpi, dpi)
    
    # Draw the barcode onto the new image
    draw = ImageDraw.Draw(final_image)
    barcode_width, barcode_height = raw_image.size

    # Center the barcode on the new image
    x_pos = (desired_width - barcode_width) // 2
    y_pos = (desired_height - barcode_height) // 2

    draw.bitmap((x_pos, y_pos), raw_image, fill='black')

    # Save the final image
    final_image.save(output_filename + ".png")

    return output_filename