How to create a png image containing a fragment of source code ? Well, don't do it yourself, the pygments module contains all the necessary tools. The example below shows how to produce a png image from python code, but pygments supports lexers for many other languages and its formatter classes can produce other image formats too. The ImageFormatter class allows to set various parameters of the resulting images. See the options here http://pygments.org/docs/formatters/#formatter-classes .