1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
from itertools import product
from typing import List from reportlab.lib.pagesizes import A4 from reportlab.graphics.shapes import Drawing, String from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget from reportlab.graphics import renderPDF from reportlab.pdfgen.canvas import Canvas
PAGESIZE = A4 NUM_LABELS_X = 3 NUM_LABELS_Y = 5 BAR_WIDTH = 1.5 BAR_HEIGHT = 51.0 TEXT_Y = 80 BARCODE_Y = 17
LABEL_WIDTH = PAGESIZE[0] / NUM_LABELS_X LABEL_HEIGHT = PAGESIZE[1] / NUM_LABELS_Y SHEET_TOP = PAGESIZE[1]
def codes(number): """ Generate all the possible barcodes params number: the range number of each position """ for barcode in product(range(10), repeat = number): yield "".join(map(str, barcode))
def label(ean13: str, description: str) -> Drawing: """ Generate a drawing with EAN-13 barcode and descriptive text. :param ean13: The EAN-13 Code. :type ean13: str :param description: Short product description. :type description: str :return: Drawing with barcode and description :rtype: Drawing """ print(ean13) text = String(0, TEXT_Y, description, fontName="Helvetica", fontSize=10, textAnchor="middle") text.x = LABEL_WIDTH / 2
barcode = Ean13BarcodeWidget(ean13) barcode.barWidth = BAR_WIDTH barcode.barHeight = BAR_HEIGHT x0, y0, bw, bh = barcode.getBounds() barcode.x = (LABEL_WIDTH - bw) / 2 barcode.y = BARCODE_Y label_drawing = Drawing(LABEL_WIDTH, LABEL_HEIGHT) label_drawing.add(text) label_drawing.add(barcode) return label_drawing
def fill_sheet(canvas: Canvas, label_drawings: List[Drawing]): """ Simply fill the given ReportLab canvas with label drawings. :param canvas: The ReportLab canvas :type canvas: Canvas :param label_drawing: Contains Drawing of configured size :type label_drawing: Drawing """ index = 0 for u in range(0, NUM_LABELS_Y): for i in range(0, NUM_LABELS_X): x = i * LABEL_WIDTH y = SHEET_TOP - LABEL_HEIGHT - u * LABEL_HEIGHT if index >= len(label_drawings): break renderPDF.draw(label_drawings[index], canvas, x, y) index += 1
if __name__ == '__main__': raw_codes = [code for code in codes(3)] labels = [label("490177241" + code, '') for code in raw_codes[:200]] total = NUM_LABELS_X * NUM_LABELS_Y page = 1 while labels: canvas = Canvas("{}.pdf".format(page), pagesize=PAGESIZE) page += 1 fill_sheet(canvas, labels[:min(total, len(labels))]) canvas.save() labels = labels[min(total, len(labels)):]
|