Search code examples
python-sphinxrestructuredtext

Sphinx Doc - How do I render an animated GIF when building for HTML but a PNG when building for latexpdf?


As title states, I'm using sphinx-doc and I really want to conditionally render static PNGs when the build output is latexpdf and animated GIFs when built for the web.

Ideally, it would be nice to be able to do this in the rst file itself somehow... semantically a:

if builder == html: .. image: blah blah elif builder == latexpdf: .. image: blah blah


Solution

  • From the Sphinx documentation for images:

    Sphinx extends the standard docutils behavior by allowing an asterisk for the extension:

    .. image:: gnu.*
    

    Sphinx then searches for all images matching the provided pattern and determines their type. Each builder then chooses the best image out of these candidates. For instance, if the file name gnu.* was given and two files gnu.pdf and gnu.png existed in the source tree, the LaTeX builder would choose the former, while the HTML builder would prefer the latter. Supported image types and choosing priority are defined at Available builders.

    To customize the "best image" order for a given builder, edit your conf.py to override the StandaloneHTMLBuilder class with the supported_image_types order you prefer.

    from sphinx.builders.html import StandaloneHTMLBuilder
    StandaloneHTMLBuilder.supported_image_types = [
        'image/svg+xml',
        'image/gif',
        'image/png',
        'image/jpeg'
    ]