WakeLift
wakelift / posts /

Sphinxcontrib-Proceduralimage: Embed procedurally generated images into your sphinx documentation

For the "top secret" project I'm working on right now, I wanted to embed pictures generated by the software I'm documenting right into the documentation. However, I didn't want to generate the picture once, paste it in and forget about it. That's why I started my new little side-project sphinxcontrib-proceduralimage.

Since I was already very amazed by how extremely cool having doctests in the documentation is, I decided to do it in a similar way with sphinxcontrib-proceduralimage. You can create a picture in your documentation by writing a block of python code, that at the end has local variables image_data and alt set. The content of image_data is PNG data, that will be embedded as-is into the documentation result. This is an example with a QPainter:

.. proceduralimage::

    from PySide.QtCore import *
    from PySide.QtGui import *

    # in order for QPainter to get fonts, we need a QApplication
    app = QApplication([])

    # create an image
    image = QImage(QSize(100, 100), Qt.Format_RGB32)
    painter = QPainter(image)

    painter.setPen(QColor("red"))
    painter.drawRect(QRect(10, 10, 20, 20))
    painter.setBrush(QColor("green"))
    painter.setPen(QColor("blue"))
    painter.drawRect(QRect(20, 20, 30, 30))
    painter.drawText(QRect(0, 0, 100, 100), Qt.AlignCenter,
                     "Test!")
    painter.end()

    # save the qimage into a string buffer
    buf = QBuffer()
    buf.open(QIODevice.ReadWrite)
    image.save(buf, "PNG")
    buf.close()
    image_data = str(buf.data())
    alt = "fancy example image"

This is what I used proceduralimage for in my documentation:

This works both with html and latex output. The code is almost a straight copy-paste of sphinx.ext.graphviz.