How to create floating figures in reStructuredText / Sphinx?

て烟熏妆下的殇ゞ 提交于 2019-12-04 04:58:31

So, I did some research into reStructuredText and it seems what you want is not actually possible.

The documentation for the figure and the image directives never mention the ability to wrap text around the object.

This might be a feature request to provide to the Sphinx developers although I suspect they'll reject it because it isn't explicitly mentioned in the rst specification.

I was hoping the bounty would garner this some attention but I suspect is hasn't.

shubham

Though it is too late but maybe the answer would help future people.

You can use the sidebar directive to put the image.

.. sidebar:: mandatory_title. Use can use image caption here

     .. Figure:: 1.png

In order to deal with images as they were part of the text you may actually use 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

paddyg

If anyone else runs into this problem then this bit of code might be a help. I decided that I didn't want to hack the actual sphinx code so I made a very short python script applied to the generated _build/latex/pi3d_book.tex to convert the \includegraphics that had \hfill before or after into wrapped images. There will be lots of things that stop this working such as putting images inside lists or scaling images. The sphinx directives in my rst are like

.. image:: perspective.png
   :align: right

You obviously have to change the file names and paths to suit your setup. From my spinx project I run

$ make latexpdf
$ python wrapfix.py # or whatever you call this file

program listing of wrapfix.py

import subprocess

with open("_build/latex/pi3d_book.tex", "r") as f:
  tx = f.read().splitlines()

txnew = []
flg1 = True
for line in tx:
  if line == "" and flg1:
    txnew += ["\\usepackage{wrapfig}",""]
    flg1 = False # just do this once before first blank line
  elif "includegraphics{" in line and "hfill" in line:
    fname = line.split("{")[2].split("}")[0]
    if line.startswith("{\\hfill"): # i.e. right justify
      fl_type = "R"
    else:
      fl_type = "L"
    txnew += ["\\begin{wrapfigure}{" + fl_type + "}{0.35\\textwidth}",
              "\\includegraphics[width = 0.3\\textwidth]{" + fname + "}",
              "\\end{wrapfigure}"]
  else:
    txnew += [line]

txnew = "\n".join(txnew)
with open("_build/latex/pi3d_book.tex", "w") as fo:
  fo.write(txnew)

subprocess.Popen(["pdflatex", "pi3d_book"], cwd="/home/jill/pi3d_book/_build/latex")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!