5.2.3 Generating Images

Not all output types that you might render are going to support everything that LaTeX is capable of. For example, HTML has no way of representing equations, and most output types won’t be capable of rendering LaTeX’s picture environment. In cases like these, you can let plasTeX generate images of the document node. Generating images is done with a subclass of plasTeX.Imagers.Imager. The imager is responsible for creating a LaTeX document from the requested document fragments, compiling the document and converting each page of the output document into individual images. Currently, there are two Imager subclasses included with plasTeX. Each of them use the standard LaTeX compiler to generate a DVI file. The DVI file is then converted into images using one of the available imagers (see section 2.1.6 on how to select different imagers).

To generate an image of a document node, simply access the image property during the rendering process. This property will return an plasTeX.Imagers.Image instance. In most cases, the image file will not be available until the rendering process is finished since most renderers will need the generated LaTeX document to be complete before compiling it and generating the final images.

The example below demonstrates how to generate an image for the equation environment.

# Import renderer from first renderer example
from MyRenderer import Renderer

from plasTeX.TeX import TeX

def handle_equation(node):
    return u'<div><img src="%s"/></div>' % node.image.url

# Instantiate a TeX processor and parse the input text
tex = TeX()

Previous paragraph.

\Sigma_{x=0}^{x+n} = \beta^2

Next paragraph.

document = tex.parse()

# Instantiate the renderer
renderer = Renderer()

# Insert the rendering method into all of the environments that might need it
renderer['equation'] = handle_equation
renderer['displaymath'] = handle_equation
renderer['eqnarray'] = handle_equation

# Render the document

The rendered output looks like the following, and the image is generated is located in ‘images/img-0001.png’.

Previous paragraph.
<div><img src="images/img-0001.png"/></div>
Next paragraph.

The names of the image files are determined by the document’s configuration. The filename generator is very powerful, and is in fact, the same filename generator used to create the other output filenames. For more information on customizing the image filenames see section 2.1.6.

In addition, the image types are customizable as well. plasTeX uses the Python Imaging Library (PIL) to do the final cropping and saving of the image files, so any image format that PIL supports can be used. The format that PIL saves the images in is determined by the file extension in the generated filenames, so you must use a file extension that PIL recognizes.

It is possible to write your own Imager subclass if necessary. See the Imager API documentation for more information (see 6.7).