Generate Wallpapers Using Python + Inkscape

Posted on April 6, 2015

I started learning Chinese last year. I learned that to have a very basic knowledge of the language you have to learn thousands of Chinese characters. So I had to figure out how to expose myself to the characters daily. I downloaded a list of the more frequent Chinese characters, and designed a wallpaper (using Inkscape) for each character, in the center of the Wallpaper there is the Chinese character, in the top left corner the pinyin word for the character, and in the bottom left corner the meaning in English, but after creating some wallpapers I thought it should be a better way to generate the wallpapers automatically.

Inkscape is a vector design tool, it uses a format called SVG, it’s just an XML-like file. We can generate text files using python right?, the problem is that SVG files cannot be used as wallpapers (at least not on Windows!), so I had to find if Inkscape can be called in the command line and send a command to generate a bitmap file from the SVG. It can be done using command:

$ inkscape -z -f [SVG File] -w [WIDTH] -j -e [Output file]

I created a Python script to generate the SVG file containing the chinese character, the Pinyin and it’s meaning in English, this script receives the Inkscape binary path, then the script uses Inkscape to generate the bitmap file.

Here is an example of a wallpaper generated by the script:

Here is the source code:

# coding=utf-8

import os
import codecs
import sys

def repl(data):
    REPL = '{{replace}}'
    svg_file = open('template.svg', 'r')
    svg_data =

    total = len(data)
    i = 0
    while svg_data.find(REPL) > 0:
        print svg_data.find(REPL)
        print total, i
        i += 1
        if i <= total:
            svg_data = svg_data.replace(REPL, data[i-1], 1)
            print svg_data.find(REPL)
    return svg_data

def get_ink_path():
    USAGE = """
\tpython [Inkscape executable path]
    if len(sys.argv) != 2:
        print USAGE
        return sys.argv[1]

if __name__ == '__main__':
    ink_path = get_ink_path()

    characters ='characters.txt', 'r', encoding='utf-16')

    c = 0
    counter = 0

    labels = ['character', 'pinyin', 'meaning']
    data = {}

    for line in characters:
        data[labels[c]] = line.strip()
        c +=1 

        if c == 3: 
            counter +=1

            svg_code = repl([data['character'], data['character'], data['pinyin'], data['meaning']])

            out ='out.svg', 'w', encoding='utf-16')

            command = '%s -z -f out.svg -w 1600 -j -e images\%s' % (ink_path, str(counter) )
            command = command + '.png'

            print command


            c = 0

This script is on Github