2A.soft - Convert a notebook into a document#

Links: notebook, html, python, slides, GitHub

A couple of tricks to convert notebook such as convert a notebook into RST or HTML, get the notebook name.

First, let’s retrieve the notebook name (see How to I get the current IPython Notebook name):

%%javascript
var kernel = IPython.notebook.kernel;
var body = document.body,
    attribs = body.attributes;
var command = "theNotebook = " + "'"+attribs['data-notebook-name'].value+"'";
kernel.execute(command);
<IPython.core.display.Javascript object>
if "theNotebook" in locals():
    a = theNotebook
else:
    a = None
a
'notebook_convert.ipynb'

On Windows, you might need to execute the following trick (see Pywin32 does not find its DLL).

import sys
if sys.platform.startswith("win"):
    from pyquickhelper.helpgen.utils_pywin32 import import_pywin32
    import_pywin32()

Then, we call the following code:

from nbconvert import HTMLExporter
exportHtml = HTMLExporter()
if a is not None:
    body,resources = exportHtml.from_filename(theNotebook)
    with open("conv_notebook.html", "w", encoding="utf8") as f:
        f.write(body)

We can do it with the RST format (see RSTExporter).

from nbconvert import RSTExporter
exportRst = RSTExporter()
if a is not None:
    body,resources = exportRst.from_filename(theNotebook)
    with open("conv_notebook.rst", "w", encoding="utf8") as f:
        f.write(body)

Finally, if you want to retrieve the download a local file such as the RST conversion for example:

from IPython.display import FileLink
FileLink("conv_notebook.rst")
conv_notebook2.rst

And the second link:

FileLink("conv_notebook.html")
conv_notebook.html