Building an epub from a single ReStructuredText file
The sphinx documentation generator is a an excellent tool. It was written to generate documentation for Python, but is used by many other projects as well. Its source format is ReStructuredText.
These webpages are written in ReStructuredText as well, and I also use this format for other bits and pieces. On occasion, I want to convert a single ReStructuredText file to an epub. This article documents how to do that.
To build an epub with sphinx, we need two directories, a source
and an
output
.
The source
directory should contain at least two files; conf.py
containing the settings for the epub conversion, and index.rst
containing
the main text.
We start in the directory where the ReStructuredText files are stored. Text between angle brackets are placeholders.
First we create the directory structure:
TMPDIR=`mktemp -d` mkdir -p ${TMPDIR}/source mkdir -p ${TMPDIR}/output/_static
Then we create the configuration file:
CONF=${TMPDIR}/source/conf.py echo "author = '<surname, given-name>'" > ${CONF} echo "copyright = '© 2021, <author>'" >> ${CONF} echo "epub_title = '"`head -n 1 <foo.rst>`"'" >> ${CONF} echo "epub_use_index = False" >> ${CONF} echo "epub_publisher = 'https://<foo.bar.org>/'" >> ${CONF} echo "epub_uid = 'pub-id'" >> ${CONF} echo "epub_identifier = 'sha256:"`sha256 -q <foo.rst>`"'" >> ${CONF} echo "project = '<foo>'" >> ${CONF}
For the unique identifier (epub_identifier
) we use the SHA256 checksum of the
source document.
Copy the source file, build the epub and clean up:
cp <foo.rst> ${TMPDIR}/source/index.rst sphinx-build -b epub ${TMPDIR}/source ${TMPDIR}/output && \ mv ${TMPDIR}/output/*.epub . && rm -rf ${TMPDIR}
For comments, please send me an e-mail.
Related articles
- Making my first e-book
- Command-line versus GUI program
- Creating a nomogram with Python and Postscript