Skip to content

Instantly share code, notes, and snippets.

@Chaz6
Last active June 13, 2025 20:11
Show Gist options
  • Save Chaz6/545e54160580a8e4b36c4b75469e7690 to your computer and use it in GitHub Desktop.
Save Chaz6/545e54160580a8e4b36c4b75469e7690 to your computer and use it in GitHub Desktop.
Generate a datmatrix label from input
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "ppf.datamatrix",
# "reportlab",
# "setuptools",
# ]
# ///
import argparse
from io import BytesIO
from reportlab.pdfgen.canvas import Canvas
from sys import stdin, stdout
from ppf.datamatrix.datamatrix import DataMatrix
padding_pct = 15
width = 1.0
height = 1.0
units = "inches"
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("infile", nargs="?", type=argparse.FileType("r"), default=stdin.buffer)
parser.add_argument(
"outfile", nargs="?", type=argparse.FileType("wb"), default=stdout
)
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
)
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 line in args.infile:
draw_barcode(c, w, h, line.strip())
c.save()
args.outfile.write(io.getbuffer())
args.infile.close()
args.outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment