Skip to content

Instantly share code, notes, and snippets.

@sandorex
Last active December 20, 2021 07:51
Show Gist options
  • Save sandorex/ce96cdb56bc963324355c80798bb04c3 to your computer and use it in GitHub Desktop.
Save sandorex/ce96cdb56bc963324355c80798bb04c3 to your computer and use it in GitHub Desktop.
Script for templating SVGs
#!/usr/bin/env python3
# label-maker.py: A little script i wrote to template SVGs and convert them to
# images so i could make custom labels without knowing how to
# use inkscape, photoshop and the like
from string import Template
import csv, os
# NOTE: pyvips needs vips-dev to be installed and in PATH
import pyvips
# === OPTIONS === #
DPI = 1200
TEMPLATE_FILE = 'template.svg'
DATA_FILE = 'data.csv'
OUTPUT_FILENAME_FORMAT = 'label-{VALUE}.jpg' # NOTE: you can use any value from
# the DATA file
OUTPUT_DIRECTORY = 'labels'
# === THE CODE === #
raw_template = ""
with open(TEMPLATE_FILE) as file:
raw_template = file.read()
os.makedirs(OUTPUT_DIRECTORY, exist_ok=True)
with open(DATA_FILE, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
img = pyvips.Image.svgload_buffer(
str.encode(Template(raw_template).safe_substitute(row)),
dpi = DPI
)
img.write_to_file(os.path.join(OUTPUT_DIRECTORY, OUTPUT_FILENAME_FORMAT.format(**row)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment