Home‎ > ‎

Using Sphinx with SVG and LaTeX PDF output

I was recently testing Sphinx as a way to build PDF files when I came across a gaping deficiency when it comes to SVG files.  In short, LaTeX does't support SVG and the Sphinx LaTeX builder fails when it finds one.

Fortunately, there is an easy workaround using the makefile.  We can use Inkscape to convert our SVG files to PDF files at build time and add this as a dependency step in the Make file.

First, add the following lines to the variables definition portion of the makefile for your Sphinx project:

SOURCEDIR     = source
#IMAGEDIRS can be a list of directories that contain SVG files and are relative to the SOURCEDIR
IMAGEDIRS      = _images _images2 ...

# SVG to PDF conversion
SVG2PDF       = inkscape
SVG2PDF_FLAGS =

Next, add the following lines after the help: section.

# Pattern rule for converting SVG to PDF
%.pdf : %.svg
    $(SVG2PDF) -f $< -A $@

# Build a list of SVG files to convert to PDFs
PDFs := $(foreach dir, $(IMAGEDIRS), $(patsubst %.svg,%.pdf,$(wildcard $(SOURCEDIR)/$(dir)/*.svg)))

# Make a rule to build the PDFs
images: $(PDFs)

Update the clean: target to clean-up the generated PDFs.  PDFs not built from the source SVG files will not be deleted.

clean:
    -rm -rf $(BUILDDIR)/*
    -rm $(PDFs)

Finally, add a dependency to the PDFs rule in the latex and latexpdf target lines.

...
latex: $(PDFs)
...
...
...

latexpdf: $(PDFs)
...


Sphinx extends the docutils reStructured text image directive to support wildcard (*) options.  This means Sphinx will automagically choose the best image option type for a given output target.  Wa-la!  We can use SVG files embedded in our HTML output and get those automatically converted to PDF for inclusion in latexpdf output.  The make file automatically ensures our PDFs are updated if our SVG source file changes.

Use my_image.* (instead of my_image.svg) in your .rst source files to make Sphinx automagically choose the appropriate image format for the target build.


Comments