#!/usr/bin/env python3 """ stickers.cy print-file builder, v1.0 (2026-11-15) Turns an artwork image into a print-ready PDF for Roland VersaWorks: - the artwork (flattened on white: white pixels = no ink) - CutContour : hairline cut line (spot colour, stroke only), offset around the artwork - RDG_WHITE : white ink layer (spot colour, fill only), choked slightly inside the artwork - RDG_Gloss : gloss ink layer (spot colour, fill only) All spot objects are set to overprint. Also writes NAME_preview.png to show the user. Needs: numpy, pillow, scipy, contourpy (ships with matplotlib), reportlab pip install numpy pillow scipy contourpy reportlab Examples # 60 mm die-cut sticker on clear vinyl, white under the art, gloss on the art python3 prepare_print_file.py --art logo.png --width-mm 60 --white art --gloss art --out bakery-60mm # white vinyl, cut only, 2.5 mm border python3 prepare_print_file.py --art logo.png --width-mm 80 --cut-offset-mm 2.5 --out logo-80mm # white sticker look on clear vinyl (white under the whole sticker incl. border) python3 prepare_print_file.py --art logo.png --width-mm 60 --white full --out logo-clear # print on an object / panel, no cut python3 prepare_print_file.py --art plaque.png --width-mm 150 --no-cut --white art --out plaque """ import argparse import sys try: import numpy as np from PIL import Image, ImageDraw from scipy.ndimage import distance_transform_edt as edt, gaussian_filter import contourpy from contourpy import FillType from reportlab.pdfgen import canvas from reportlab.lib.colors import CMYKColorSep from reportlab.lib.units import mm from reportlab.lib.utils import ImageReader except ImportError as e: # pragma: no cover sys.exit(f"Missing library ({e.name}). Run: pip install numpy pillow scipy contourpy reportlab") # Exact VersaWorks spot names (case-sensitive). Alternate CMYK values only affect on-screen previews. CUT = CMYKColorSep(0, 1, 0, 0, spotName="CutContour") WHITE = CMYKColorSep(0, 0, 0, 0.12, spotName="RDG_WHITE") GLOSS = CMYKColorSep(0.25, 0, 0, 0, spotName="RDG_Gloss") def load_mask(img, bg_threshold): """True where the artwork has ink. Uses alpha if present, else treats near-white as background.""" rgba = img.convert("RGBA") a = np.asarray(rgba) alpha = a[..., 3] has_alpha = alpha.min() < 250 if has_alpha: mask = alpha >= 128 else: mask = (a[..., :3] < bg_threshold).any(axis=2) flat = Image.new("RGB", rgba.size, (255, 255, 255)) flat.paste(rgba, mask=rgba.split()[3]) return mask, flat, has_alpha def rdp(pts, eps): """Ramer-Douglas-Peucker simplification of a closed ring (Nx2).""" if len(pts) < 5: return pts keep = np.zeros(len(pts), bool) keep[0] = keep[-1] = True stack = [(0, len(pts) - 1)] while stack: s, e = stack.pop() if e <= s + 1: continue a, b = pts[s], pts[e] seg = b - a n = np.hypot(*seg) v = pts[s + 1:e] - a d = np.abs(seg[0] * v[:, 1] - seg[1] * v[:, 0]) / n if n > 0 else np.hypot(v[:, 0], v[:, 1]) i = int(np.argmax(d)) if d[i] > eps: m = s + 1 + i keep[m] = True stack += [(s, m), (m, e)] return pts[keep] def regions(field, lower, upper, outer_only, eps_px, min_area_px): """Filled contour of lower <= field <= upper -> list of rings (pixel coords).""" gen = contourpy.contour_generator(z=field, fill_type=FillType.OuterOffset) pts_list, offs_list = gen.filled(lower, upper) rings = [] for pts, offs in zip(pts_list, offs_list): bounds = list(zip(offs[:-1], offs[1:])) if outer_only: bounds = bounds[:1] for s, e in bounds: ring = pts[s:e] x, y = ring[:, 0], ring[:, 1] area = 0.5 * abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) if area >= min_area_px: rings.append(rdp(ring, eps_px)) return rings def main(): ap = argparse.ArgumentParser(description="stickers.cy print-file builder") ap.add_argument("--art", required=True, help="artwork image (PNG with transparency is best)") ap.add_argument("--width-mm", type=float, help="final width of the artwork in mm") ap.add_argument("--height-mm", type=float, help="final height of the artwork in mm (use instead of width)") ap.add_argument("--cut-offset-mm", type=float, default=2.0, help="cut line distance from the artwork edge (default 2)") ap.add_argument("--no-cut", action="store_true", help="no cut line (banners, panels, objects)") ap.add_argument("--one-piece", action="store_true", help="join separate parts of the design into one sticker shape") ap.add_argument("--white", default="none", help="none | art (under inked areas) | full (under the whole cut shape)") ap.add_argument("--white-choke-mm", type=float, default=0.15, help="pull white in from the art edge (default 0.15)") ap.add_argument("--gloss", default="none", help="none | art | full | path to a mask image (black = gloss, same size as art)") ap.add_argument("--bg-threshold", type=int, default=245, help="for images without transparency: brighter than this = background") ap.add_argument("--margin-mm", type=float, default=3.0, help="empty margin around the cut line") ap.add_argument("--out", required=True, help="output name without extension") a = ap.parse_args() img = Image.open(a.art) mask, flat, has_alpha = load_mask(img, a.bg_threshold) h_px, w_px = mask.shape if not mask.any(): sys.exit("No artwork found (image is empty or entirely background).") if a.width_mm: ppm = w_px / a.width_mm elif a.height_mm: ppm = h_px / a.height_mm else: sys.exit("Give --width-mm or --height-mm (the final printed size).") dpi = ppm * 25.4 warn = [] if dpi < 300: warn.append(f"Artwork is {dpi:.0f} dpi at this size; 300 dpi is recommended (150 is the minimum for banners).") if not has_alpha: warn.append(f"No transparency: pixels brighter than {a.bg_threshold} were treated as background.") off_px = 0 if a.no_cut else a.cut_offset_mm * ppm pad = int(np.ceil(off_px + a.margin_mm * ppm)) + 2 m = np.pad(mask, pad) H, W = m.shape dist_out = edt(~m) # distance from the artwork, outside dist_in = edt(m) # distance from the background, inside eps = 0.02 * ppm # simplify paths to 0.02 mm min_area = (0.3 * ppm) ** 2 cut_field = dist_out if a.one_piece and not a.no_cut: # morphological closing: grow until the parts touch, then shrink back by the same amount for extra_mm in (1, 2, 4, 6, 9, 13, 20): r = extra_mm * ppm closed = edt(dist_out <= off_px + r) >= r n_parts = len(regions(np.where(closed, 0.0, 1.0), -1, 0.5, True, eps, min_area)) if n_parts <= 1: r *= 1.6 # a little more than the minimum, for rounder bridges closed = edt(dist_out <= off_px + r) >= r break # smooth signed distance of the joined shape; the cut runs along its zero line sd = gaussian_filter(edt(~closed) - edt(closed), 1.2) cut_field, cut_lo, cut_hi = sd, -1e9, 0.0 if n_parts > 1: warn.append("The design has parts too far apart to join into one sticker; they stay separate.") else: cut_lo, cut_hi = -1, off_px cut_rings = [] if a.no_cut else regions(cut_field, cut_lo, cut_hi, True, eps, min_area) def layer(mode, choke_mm): if mode == "none": return [] if mode == "art": return regions(dist_in, max(choke_mm * ppm, 0.5), 1e9, False, eps, min_area) if mode == "full": return cut_rings if cut_rings else regions(dist_in, 0.5, 1e9, False, eps, min_area) gm = np.asarray(Image.open(mode).convert("L").resize((w_px, h_px))) < 128 cover = gm.mean() if cover == 0: warn.append("The gloss mask is empty (no black areas); no gloss was added.") elif cover > 0.95: warn.append("The gloss mask is almost entirely black, so gloss covers the whole artwork. Check the mask: black = gloss, white = no gloss.") return regions(edt(np.pad(gm, pad)), 0.5, 1e9, False, eps, min_area) white_rings = layer(a.white, a.white_choke_mm) gloss_rings = layer(a.gloss, 0) page_w, page_h = W / ppm * mm, H / ppm * mm to_pdf = lambda x, y: (x / ppm * mm, (H - y) / ppm * mm) c = canvas.Canvas(a.out + ".pdf", pagesize=(page_w, page_h)) c.setTitle(f"{a.out} - stickers.cy print file") c.setAuthor("stickers.cy print-file builder 1.0") c.drawImage(ImageReader(flat), pad / ppm * mm, pad / ppm * mm, w_px / ppm * mm, h_px / ppm * mm) def path_of(rings): p = c.beginPath() for r in rings: x0, y0 = to_pdf(*r[0]) p.moveTo(x0, y0) for x, y in r[1:]: p.lineTo(*to_pdf(x, y)) p.close() return p c.saveState() c.setFillOverprint(True) c.setStrokeOverprint(True) c.setOverprintMask(1) if white_rings: c.setFillColor(WHITE) c.drawPath(path_of(white_rings), stroke=0, fill=1, fillMode=0) # 0 = even-odd (keeps holes) if gloss_rings: c.setFillColor(GLOSS) c.drawPath(path_of(gloss_rings), stroke=0, fill=1, fillMode=0) if cut_rings: c.setStrokeColor(CUT) c.setLineWidth(0.25) c.setLineJoin(1) c.drawPath(path_of(cut_rings), stroke=1, fill=0) c.restoreState() c.showPage() c.save() # preview for the user: checker = no ink (vinyl/material shows), grey = white ink, white diagonal lines = gloss, magenta = cut s = max(1, int(round(ppm * 25.4 / 250))) # preview at ~250 dpi pv = Image.new("RGB", (W, H), (255, 255, 255)) ck = ImageDraw.Draw(pv) step = max(8, int(2 * ppm)) for yy in range(0, H, step): for xx in range(0, W, step): if (xx // step + yy // step) % 2: ck.rectangle([xx, yy, xx + step - 1, yy + step - 1], fill=(232, 236, 234)) def eo_mask(rings): acc = np.zeros((H, W), bool) for r in rings: mk = Image.new("1", (W, H), 0) ImageDraw.Draw(mk).polygon([tuple(p) for p in r], fill=1) acc ^= np.asarray(mk, bool) return Image.fromarray((acc * 255).astype("uint8"), "L") if white_rings: pv.paste((198, 198, 198), (0, 0), eo_mask(white_rings)) art = Image.new("RGBA", (W, H), (0, 0, 0, 0)) art.paste(img.convert("RGBA"), (pad, pad)) pv.paste(art, (0, 0), art) if gloss_rings: hatch = Image.new("L", (W, H), 0) hd = ImageDraw.Draw(hatch) gap = max(6, int(ppm * 1.2)) for k in range(-H, W, gap): hd.line([(k, 0), (k + H, H)], fill=255, width=max(1, int(ppm * 0.25))) gmask = Image.fromarray(np.minimum(np.asarray(hatch), np.asarray(eo_mask(gloss_rings))), "L") pv.paste((255, 255, 255), (0, 0), gmask) cd = ImageDraw.Draw(pv) for r in cut_rings: cd.line([tuple(p) for p in r] + [tuple(r[0])], fill=(228, 0, 124), width=max(2, int(ppm * 0.25))) pv = pv.resize((max(1, W // s), max(1, H // s)), Image.LANCZOS) pv.save(a.out + "_preview.png") print(f"Wrote {a.out}.pdf and {a.out}_preview.png") print(f"Page {W/ppm:.1f} x {H/ppm:.1f} mm | artwork {w_px/ppm:.1f} x {h_px/ppm:.1f} mm at {dpi:.0f} dpi") print(f"CutContour paths: {len(cut_rings)} | RDG_WHITE: {'yes' if white_rings else 'no'} | RDG_Gloss: {'yes' if gloss_rings else 'no'}") print("Preview legend: checker = no ink, grey = white ink, white diagonal lines = gloss, magenta line = cut.") print("Note: PDF viewers without overprint preview draw the white/gloss layers on top of the art. That is expected; show the user the preview PNG.") for w in warn: print("WARNING:", w) if __name__ == "__main__": main()