Skip to content

Instantly share code, notes, and snippets.

@matteohoeren
Created June 17, 2025 08:38
Show Gist options
  • Save matteohoeren/4f9e5f26effd657e3348344f387a07a0 to your computer and use it in GitHub Desktop.
Save matteohoeren/4f9e5f26effd657e3348344f387a07a0 to your computer and use it in GitHub Desktop.
Python3 (WhatsApp) Sticker Compilation to A4
import os
import base64
import mimetypes
import math
import subprocess
from PIL import Image
from lxml import etree
# WARNING: This script was vibe coded. It takes a folder of stickers and puts them onto an A4 canvas for easy printing
# === CONFIGURATION ===
image_folder = "stickers"
output_basename = "sticker_layout"
image_size_cm = 5
page_width_cm = 21
page_height_cm = 29.7
# === CONSTANTS ===
px_per_cm = 96 / 2.54
image_size_px = image_size_cm * px_per_cm
page_width_px = page_width_cm * px_per_cm
page_height_px = page_height_cm * px_per_cm
cols = int(page_width_cm // image_size_cm)
rows = int(page_height_cm // image_size_cm)
images_per_page = cols * rows
# === IMAGE COLLECTION ===
supported_formats = ('.png', '.jpg', '.jpeg', '.svg', '.webp')
files = sorted(f for f in os.listdir(image_folder) if f.lower().endswith(supported_formats))
total_pages = math.ceil(len(files) / images_per_page)
# === Convert .webp to .png ===
converted_files = []
for f in files:
path = os.path.join(image_folder, f)
if f.lower().endswith('.webp'):
png_path = os.path.splitext(path)[0] + ".png"
img = Image.open(path).convert("RGBA")
img.save(png_path)
converted_files.append(os.path.basename(png_path))
else:
converted_files.append(f)
print(f"📦 Total images after conversion: {len(converted_files)} across {total_pages} pages")
# === FUNCTION TO CREATE A PAGE ===
def create_svg_page(images, page_index):
svg_ns = "http://www.w3.org/2000/svg"
xlink_ns = "http://www.w3.org/1999/xlink"
nsmap = {None: svg_ns, 'xlink': xlink_ns}
svg = etree.Element("svg", nsmap=nsmap)
svg.set("width", f"{page_width_px}px")
svg.set("height", f"{page_height_px}px")
svg.set("viewBox", f"0 0 {page_width_px} {page_height_px}")
for i, filename in enumerate(images):
col = i % cols
row = i // cols
x = col * image_size_px
y = row * image_size_px
filepath = os.path.join(image_folder, filename)
mime_type, _ = mimetypes.guess_type(filepath)
if not mime_type:
print(f"⚠️ Skipping {filename}: unknown MIME type")
continue
with open(filepath, "rb") as f:
encoded = base64.b64encode(f.read()).decode("utf-8")
href = f"data:{mime_type};base64,{encoded}"
image = etree.Element("{%s}image" % svg_ns)
image.set("x", str(x))
image.set("y", str(y))
image.set("width", str(image_size_px))
image.set("height", str(image_size_px))
image.set("{%s}href" % xlink_ns, href)
svg.append(image)
svg_filename = f"{output_basename}_page{page_index+1}.svg"
etree.ElementTree(svg).write(svg_filename, pretty_print=True, xml_declaration=True, encoding="UTF-8")
print(f"🖼️ Created {svg_filename}")
return svg_filename
# === PROCESS EACH PAGE ===
output_svgs = []
for page_index in range(total_pages):
start = page_index * images_per_page
end = start + images_per_page
page_images = converted_files[start:end]
svg_file = create_svg_page(page_images, page_index)
output_svgs.append(svg_file)
# === EXPORT TO PDF using legacy-compatible Inkscape ===
for svg_file in output_svgs:
pdf_file = svg_file.replace(".svg", ".pdf")
try:
subprocess.run(["inkscape", svg_file, "--export-type=pdf", f"--export-filename={pdf_file}"], check=True)
print(f"📄 Exported to PDF: {pdf_file}")
except subprocess.CalledProcessError:
print(f"❌ Error exporting {svg_file} to PDF")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment