Skip to content

Instantly share code, notes, and snippets.

@Chaz6
Last active June 13, 2025 20:11
Show Gist options
  • Save Chaz6/93f59e17cd0f35653514ca26ec168bc7 to your computer and use it in GitHub Desktop.
Save Chaz6/93f59e17cd0f35653514ca26ec168bc7 to your computer and use it in GitHub Desktop.
Generate random datamatrix codes for asset labels
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "ppf.datamatrix",
# "reportlab",
# "setuptools",
# "shortuuid",
# ]
# ///
import argparse
import shortuuid
from io import BytesIO
from reportlab.pdfgen.canvas import Canvas
from ppf.datamatrix.datamatrix import DataMatrix
from sys import stdout
padding_pct = 15
width = 1.0
height = 1.0
units = "inches"
DEFAULT_COPIES = 2
INCHES_TO_POINTS = 72
def draw_barcode(c: Canvas, width: float, height: float, value: str):
dmtx = DataMatrix(value).matrix
rows = len(dmtx)
px = width * (1 - (2 * padding_pct) / 100) / rows
initial = padding_pct / 100 * height
y = height - initial
for row in dmtx:
x = initial
for col in row:
if col:
c.rect(x, y, px, -px, fill=1, stroke=0)
x += px
y -= px
c.showPage()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("qty", type=int)
parser.add_argument(
"outfile", nargs="?", type=argparse.FileType("wb"), default=stdout.buffer
)
parser.add_argument(
"--width", type=float, default=width, help="width in %s" % units
)
parser.add_argument(
"--height", type=float, default=height, help="height in %s" % units
)
parser.add_argument(
"--copies", type=int, default=DEFAULT_COPIES, help="number of copies"
)
args = parser.parse_args()
w = args.width * INCHES_TO_POINTS
h = args.height * INCHES_TO_POINTS
io = BytesIO()
c = Canvas(io, pagesize=(w, h))
c.setFillColorRGB(0, 0, 0)
for _ in range(args.qty):
uuid = shortuuid.uuid()
for _ in range(args.copies):
draw_barcode(c, w, h, uuid)
c.save()
args.outfile.write(io.getbuffer())
args.outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment