Restructured Text (Sphinx) Image in Heading?

With HTML and CSS there are a number of ways to add an image to an element which yield different results. A couple that I can think of are:

  1. Use an image in place of any text. Here we keep the text, but send it off screen, so it is still accessible.

    h1 {
        background: url(images/image.jpg) no-repeat top center;
        display: block;
        text-indent: 100%;
        white-space: nowrap;
        overflow: hidden;
        width: XXpx;
        height: XXpx;
    }
    
  2. Place an image to the left of the text (or could easily be to the right)

    h1 {
        background: url(images/image.jpg) no-repeat top left;
        padding-left: XXpx;
    }
    
  3. Use a background image, behind any text

    h1 {
        background:url(images/image.jpg) no-repeat top center;
    }
    

More specific CSS selectors can be used to target only certain headers.

You can include custom CSS easily within reStructuredText documents using the raw directive, like so:

.. raw:: html

    <style>
        <!-- One of the CSS styles above. -->
    </style>

Alternatively, you can include custom CSS stylesheets from the command line using the --stylesheet option of rst2html.py.

In terms of achieving the same with PDF output, I will steal part of another one of my answers:

Obviously the above targets HTML output. However, I have not used rst2pdf, so can't comment on how the above needs to be modified to work with this program. Hopefully someone else will provide an answer to this. As far as I know, rst2pdf does support a cascading stylesheet mechanism, so it should be straightforward (for someone who knows rst2pdf style sheet syntax) to add an additional .. raw:: pdf role and to modify the above list styles.


I think that a better result could be achieved using aliases (i.e. substitutions).

Here an extract from the documentation that can be helpful:

The |biohazard| symbol must be used on containers used to
dispose of medical waste.

.. |biohazard| image:: biohazard.png

I hope this helps


This can be achieved by using a substitution in the header:

Header Text |foo|
=================

.. |foo| image:: path/to/img.png

Here foo is just an example substitution text. It can be anything, but should not start or end with a whitespace.

The abstract substitution syntax is as follows:

+-------+-----------------------------------------------------+
| ".. " | "|" substitution text "| " directive type "::" data |
+-------+ directive block                                     |
        |                                                     |
        +-----------------------------------------------------+

As we would like to insert an inline image, we should choose the image as the directive type.