Skip to content

Instantly share code, notes, and snippets.

@ksdme
Created September 24, 2024 09:09
Show Gist options
  • Save ksdme/084afcfa5d317e3d9ffb2f12f0fb0446 to your computer and use it in GitHub Desktop.
Save ksdme/084afcfa5d317e3d9ffb2f12f0fb0446 to your computer and use it in GitHub Desktop.
qr.py
from typing import BinaryIO
from dataclasses import dataclass
from fpdf import FPDF
from math import ceil
import qrcode
@dataclass
class Sticker:
code: str
def generate_stickers(items: list[Sticker], offset=0):
"""
Generate a sheet of stickers from the items.
"""
pdf = FPDF()
total_w, total_h = 210, 297
margin_x, margin_y = 12, 12
cols, rows, per_sheet = 2, 10, 20
usable_w, usable_h = (total_w - 2*margin_x), (total_h - 2*margin_y)
cell_w, cell_h = (0.9 * usable_w / 2), (0.8 * usable_h / 10)
gap_x, gap_y = (0.1 * usable_w / (cols - 1)), (0.16 * usable_h / (rows - 1))
items = [None] * offset + items
chunks = [
items[i * per_sheet : (i + 1) * per_sheet]
for i in range(ceil(len(items) / per_sheet))
]
for chunk in chunks:
pdf.add_page()
pdf.set_font("helvetica", "B", 16)
for no, sticker in enumerate(chunk):
if sticker is None:
continue
left = margin_x + (no % cols) * (cell_w + gap_x)
top = margin_y + (no // cols) * (cell_h + gap_y)
size = min(cell_w, cell_h)
qr = qrcode.make(sticker.code, border=0)
pdf.image(qr.get_image(), x=left, y=top, w=size, h=size)
gap = 6
pdf.set_xy(left + size + gap, top)
pdf.cell(cell_w - size - gap, cell_h, sticker.code)
pdf.output("code.pdf")
generate_stickers([Sticker("1"), Sticker("2")], offset=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment