Skip to main content
`Ctrl`+`K`

# Using nbconvert as a library

In this notebook, you will be introduced to the programmatic API of nbconvert and how it can be used in various contexts.

A great blog post by @jakevdp will be used to demonstrate. This notebook will not focus on using the command line tool. The attentive reader will point-out that no data is read from or written to disk during the conversion process. This is because nbconvert has been designed to work in memory so that it works well in a database or web-based environment too.

## Quick overview

Credit: Jonathan Frederic (@jdfreder on github)

The main principle of nbconvert is to instantiate an `Exporter` that controls the pipeline through which notebooks are converted.

First, download @jakevdp’s notebook (if you do not have `requests`, install it by running `pip install requests`, or if you don’t have pip installed, you can find it on PYPI):

    [1]:

    from urllib.request import urlopen

    url = "https://jakevdp.github.io/downloads/notebooks/XKCD_plots.ipynb"
    response = urlopen(url).read().decode()
    response[0:60] + " ..."

    ---------------------------------------------------------------------------
    gaierror                                  Traceback (most recent call last)
    File /usr/lib/python3.14/urllib/request.py:1321, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
       1320 try:
    -> 1321     h.request(req.get_method(), req.selector, req.data, headers,
       1322               encode_chunked=req.has_header('Transfer-encoding'))
       1323 except OSError as err: # timeout error

    File /usr/lib/python3.14/http/client.py:1358, in HTTPConnection.request(self, method, url, body, headers, encode_chunked)
       1357 """Send a complete request to the server."""
    -> 1358 self._send_request(method, url, body, headers, encode_chunked)

    File /usr/lib/python3.14/http/client.py:1404, in HTTPConnection._send_request(self, method, url, body, headers, encode_chunked)
       1403     body = _encode(body, 'body')
    -> 1404 self.endheaders(body, encode_chunked=encode_chunked)

    File /usr/lib/python3.14/http/client.py:1353, in HTTPConnection.endheaders(self, message_body, encode_chunked)
       1352     raise CannotSendHeader()
    -> 1353 self._send_output(message_body, encode_chunked=encode_chunked)

    File /usr/lib/python3.14/http/client.py:1113, in HTTPConnection._send_output(self, message_body, encode_chunked)
       1112 del self._buffer[:]
    -> 1113 self.send(msg)
       1115 if message_body is not None:
       1116
       1117     # create a consistent interface to message_body

    File /usr/lib/python3.14/http/client.py:1057, in HTTPConnection.send(self, data)
       1056 if self.auto_open:
    -> 1057     self.connect()
       1058 else:

    File /usr/lib/python3.14/http/client.py:1492, in HTTPSConnection.connect(self)
       1490 "Connect to a host on a given (SSL) port."
    -> 1492 super().connect()
       1494 if self._tunnel_host:

    File /usr/lib/python3.14/http/client.py:1023, in HTTPConnection.connect(self)
       1022 sys.audit("http.client.connect", self, self.host, self.port)
    -> 1023 self.sock = self._create_connection(
       1024     (self.host,self.port), self.timeout, self.source_address)
       1025 # Might fail in OSs that don't implement TCP_NODELAY

    File /usr/lib/python3.14/socket.py:846, in create_connection(address, timeout, source_address, all_errors)
        845 exceptions = []
    --> 846 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        847     af, socktype, proto, canonname, sa = res

    File /usr/lib/python3.14/socket.py:983, in getaddrinfo(host, port, family, type, proto, flags)
        982 addrlist = []
    --> 983 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
        984     af, socktype, proto, canonname, sa = res

    gaierror: [Errno -2] Name or service not known

    During handling of the above exception, another exception occurred:

    URLError                                  Traceback (most recent call last)
    Cell In[1], line 4
          1 from urllib.request import urlopen
          3 url = "https://jakevdp.github.io/downloads/notebooks/XKCD_plots.ipynb"
    ----> 4 response = urlopen(url).read().decode()
          5 response[0:60] + " ..."

    File /usr/lib/python3.14/urllib/request.py:187, in urlopen(url, data, timeout, context)
        185 else:
        186     opener = _opener
    --> 187 return opener.open(url, data, timeout)

    File /usr/lib/python3.14/urllib/request.py:487, in OpenerDirector.open(self, fullurl, data, timeout)
        484     req = meth(req)
        486 sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
    --> 487 response = self._open(req, data)
        489 # post-process response
        490 meth_name = protocol+"_response"

    File /usr/lib/python3.14/urllib/request.py:504, in OpenerDirector._open(self, req, data)
        501     return result
        503 protocol = req.type
    --> 504 result = self._call_chain(self.handle_open, protocol, protocol +
        505                           '_open', req)
        506 if result:
        507     return result

    File /usr/lib/python3.14/urllib/request.py:464, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
        462 for handler in handlers:
        463     func = getattr(handler, meth_name)
    --> 464     result = func(*args)
        465     if result is not None:
        466         return result

    File /usr/lib/python3.14/urllib/request.py:1369, in HTTPSHandler.https_open(self, req)
       1368 def https_open(self, req):
    -> 1369     return self.do_open(http.client.HTTPSConnection, req,
       1370                         context=self._context)

    File /usr/lib/python3.14/urllib/request.py:1324, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
       1321         h.request(req.get_method(), req.selector, req.data, headers,
       1322                   encode_chunked=req.has_header('Transfer-encoding'))
       1323     except OSError as err: # timeout error
    -> 1324         raise URLError(err)
       1325     r = h.getresponse()
       1326 except:

    URLError: <urlopen error [Errno -2] Name or service not known>

The response is a JSON string which represents a Jupyter notebook.

Next, we will read the response using nbformat. Doing this will guarantee that the notebook structure is valid. Note that the in-memory format and on disk format are slightly different. In particular, on disk, multiline strings might be split into a list of strings.

    [2]:

    import nbformat

    jake_notebook = nbformat.reads(response, as_version=4)
    jake_notebook.cells[0]

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[2], line 3
          1 import nbformat
    ----> 3 jake_notebook = nbformat.reads(response, as_version=4)
          4 jake_notebook.cells[0]

    NameError: name 'response' is not defined

The nbformat API returns a special type of dictionary. For this example, you don’t need to worry about the details of the structure (if you are interested, please see the nbformat documentation).

The nbconvert API exposes some basic exporters for common formats and defaults. You will start by using one of them. First, you will import one of these exporters (specifically, the HTML exporter), then instantiate it using most of the defaults, and then you will use it to process the notebook we downloaded earlier.

    [3]:

    from traitlets.config import Config

    # 1. Import the exporter
    from nbconvert import HTMLExporter

    # 2. Instantiate the exporter. We use the `classic` template for now; we'll get into more details
    # later about how to customize the exporter further.
    html_exporter = HTMLExporter(template_name="classic")

    # 3. Process the notebook we loaded earlier
    (body, resources) = html_exporter.from_notebook_node(jake_notebook)

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[3], line 11
          8 html_exporter = HTMLExporter(template_name="classic")
         10 # 3. Process the notebook we loaded earlier
    ---> 11 (body, resources) = html_exporter.from_notebook_node(jake_notebook)

    NameError: name 'jake_notebook' is not defined

The exporter returns a tuple containing the source of the converted notebook, as well as a resources dict. In this case, the source is just raw HTML:

    [4]:

    print(body[:400] + "...")

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[4], line 1
    ----> 1 print(body[:400] + "...")

    NameError: name 'body' is not defined

If you understand HTML, you’ll notice that some common tags are omitted, like the `body` tag. Those tags are included in the default `HtmlExporter`, which is what would have been constructed if we had not modified the `template_file`.

The resource dict contains (among many things) the extracted `.png`, `.jpg`, etc. from the notebook when applicable. The basic HTML exporter leaves the figures as embedded base64, but you can configure it to extract the figures. So for now, the resource dict should be mostly empty, except for a key containing CSS and a few others whose content will be obvious:

    [5]:

    print("Resources:", resources.keys())
    print("Metadata:", resources["metadata"].keys())
    print("Inlining:", resources["inlining"].keys())
    print("Extension:", resources["output_extension"])

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[5], line 1
    ----> 1 print("Resources:", resources.keys())
          2 print("Metadata:", resources["metadata"].keys())
          3 print("Inlining:", resources["inlining"].keys())

    NameError: name 'resources' is not defined

`Exporter`s are stateless, so you won’t be able to extract any useful information beyond their configuration. You can re-use an exporter instance to convert another notebook. In addition to the `from_notebook_node` used above, each exporter exposes `from_file` and `from_filename` methods.

## Extracting Figures using the RST Exporter

When exporting, you may want to extract the base64 encoded figures as files. While the HTML exporter does not do this by default, the `RstExporter` does:

    [6]:

    # Import the RST exproter
    from nbconvert import RSTExporter

    # Instantiate it
    rst_exporter = RSTExporter()
    # Convert the notebook to RST format
    (body, resources) = rst_exporter.from_notebook_node(jake_notebook)

    print(body[:970] + "...")
    print("[.....]")
    print(body[800:1200] + "...")

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[6], line 7
          5 rst_exporter = RSTExporter()
          6 # Convert the notebook to RST format
    ----> 7 (body, resources) = rst_exporter.from_notebook_node(jake_notebook)
          9 print(body[:970] + "...")
         10 print("[.....]")

    NameError: name 'jake_notebook' is not defined

Notice that base64 images are not embedded, but instead there are filename-like strings, such as `output_3_0.png`. The strings actually are (configurable) keys that map to the binary data in the resources dict.

Note, if you write an RST Plugin, you are responsible for writing all the files to the disk (or uploading, etc…) in the right location. Of course, the naming scheme is configurable.

As an exercise, this notebook will show you how to get one of those images. First, take a look at the `'outputs'` of the returned resources dictionary. This is a dictionary that contains a key for each extracted resource, with values corresponding to the actual base64 encoding:

    [7]:

    sorted(resources["outputs"].keys())

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[7], line 1
    ----> 1 sorted(resources["outputs"].keys())

    NameError: name 'resources' is not defined

In this case, there are 5 extracted binary figures, all `png`s. We can use the Image display object to actually display one of the images:

    [8]:

    from IPython.display import Image

    Image(data=resources["outputs"]["output_3_0.png"], format="png")

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[8], line 3
          1 from IPython.display import Image
    ----> 3 Image(data=resources["outputs"]["output_3_0.png"], format="png")

    NameError: name 'resources' is not defined

Note that this image is being rendered without ever reading or writing to the disk.

## Extracting Figures using the HTML Exporter

As mentioned above, by default, the HTML exporter does not extract images – it just leaves them as inline base64 encodings. However, this is not always what you might want. For example, here is a use case from @jakevdp:

> I write an awesome blog using Jupyter notebooks converted to HTML, and I want the images to be cached. Having one html file with all of the images base64 encoded inside it is nice when sharing with a coworker, but for a website, not so much. I need an HTML exporter, and I want it to extract the figures!

### Some theory

Before we get into actually extracting the figures, it will be helpful to give a high-level overview of the process of converting a notebook to a another format:

1. Retrieve the notebook and it’s accompanying resources (you are responsible for this).

2. Feed the notebook into the `Exporter`, which:

   1. Sequentially feeds the notebook into an array of `Preprocessor`s. Preprocessors only act on the structure of the notebook, and have unrestricted access to it.

   2. Feeds the notebook into the Jinja templating engine, which converts it to a particular format depending on which template is selected.

3. The exporter returns the converted notebook and other relevant resources as a tuple.

4. You write the data to the disk using the built-in `FilesWriter` (which writes the notebook and any extracted files to disk), or elsewhere using a custom `Writer`.

### Using different preprocessors

To extract the figures when using the HTML exporter, we will want to change which `Preprocessor`s we are using. There are several preprocessors that come with nbconvert, including one called the `ExtractOutputPreprocessor`.

The `ExtractOutputPreprocessor` is responsible for crawling the notebook, finding all of the figures, and putting them into the resources directory, as well as choosing the key (i.e. `filename_xx_y.extension`) that can replace the figure inside the template. To enable the `ExtractOutputPreprocessor`, we must add it to the exporter’s list of preprocessors:

    [9]:

    # create a configuration object that changes the preprocessors
    from traitlets.config import Config

    c = Config()
    c.HTMLExporter.preprocessors = ["nbconvert.preprocessors.ExtractOutputPreprocessor"]

    # create the new exporter using the custom config
    html_exporter_with_figs = HTMLExporter(config=c)
    html_exporter_with_figs.preprocessors

    [9]:

    ['nbconvert.preprocessors.ExtractOutputPreprocessor']

We can compare the result of converting the notebook using the original HTML exporter and our new customized one:

    [10]:

    (_, resources) = html_exporter.from_notebook_node(jake_notebook)
    (_, resources_with_fig) = html_exporter_with_figs.from_notebook_node(jake_notebook)

    print("resources without figures:")
    print(sorted(resources.keys()))

    print("\nresources with extracted figures (notice that there's one more field called 'outputs'):")
    print(sorted(resources_with_fig.keys()))

    print("\nthe actual figures are:")
    print(sorted(resources_with_fig["outputs"].keys()))

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[10], line 1
    ----> 1 (_, resources) = html_exporter.from_notebook_node(jake_notebook)
          2 (_, resources_with_fig) = html_exporter_with_figs.from_notebook_node(jake_notebook)
          4 print("resources without figures:")

    NameError: name 'jake_notebook' is not defined

## Custom Preprocessors

There are an endless number of transformations that you may want to apply to a notebook. In particularly complicated cases, you may want to actually create your own `Preprocessor`. Above, when we customized the list of preprocessors accepted by the `HTMLExporter`, we passed in a string – this can be any valid module name. So, if you create your own preprocessor, you can include it in that same list and it will be used by the exporter.

To create your own preprocessor, you will need to subclass from `nbconvert.preprocessors.Preprocessor` and overwrite either the `preprocess` and/or `preprocess_cell` methods.

## Example

The following demonstration adds the ability to exclude a cell by index.

Note: injecting cells is similar, and won’t be covered here. If you want to inject static content at the beginning/end of a notebook, use a custom template.

    [11]:

    from traitlets import Integer

    from nbconvert.preprocessors import Preprocessor

    class PelicanSubCell(Preprocessor):
        """A Pelican specific preprocessor to remove some of the cells of a notebook"""

        # I could also read the cells from nb.metadata.pelican if someone wrote a JS extension,
        # but for now I'll stay with configurable value.
        start = Integer(0, help="first cell of notebook to be converted").tag(config=True)
        end = Integer(-1, help="last cell of notebook to be converted").tag(config=True)

        def preprocess(self, nb, resources):
            self.log.info("I'll keep only cells from %d to %d", self.start, self.end)
            nb.cells = nb.cells[self.start : self.end]
            return nb, resources

Here a Pelican exporter is created that takes `PelicanSubCell` preprocessors and a `config` object as parameters. This may seem redundant, but with the configuration system you can register an inactive preprocessor on all of the exporters and activate it from config files or the command line.

    [12]:

    # Create a new config object that configures both the new preprocessor, as well as the exporter
    c = Config()
    c.PelicanSubCell.start = 4
    c.PelicanSubCell.end = 6
    c.RSTExporter.preprocessors = [PelicanSubCell]

    # Create our new, customized exporter that uses our custom preprocessor
    pelican = RSTExporter(config=c)

    # Process the notebook
    print(pelican.from_notebook_node(jake_notebook)[0])

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[12], line 11
          8 pelican = RSTExporter(config=c)
         10 # Process the notebook
    ---> 11 print(pelican.from_notebook_node(jake_notebook)[0])

    NameError: name 'jake_notebook' is not defined

## Programmatically creating templates

    [13]:

    from jinja2 import DictLoader

    dl = DictLoader(
        {
            "footer": """
    {%- extends 'lab/index.html.j2' -%}

    {% block footer %}
    FOOOOOOOOTEEEEER
    {% endblock footer %}
    """
        }
    )

    exportHTML = HTMLExporter(extra_loaders=[dl], template_file="footer")
    (body, resources) = exportHTML.from_notebook_node(jake_notebook)
    for l in body.split("\n")[-4:]:
        print(l)

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[13], line 17
          3 dl = DictLoader(
          4     {
          5         "footer": """
       (...)
         12     }
         13 )
         16 exportHTML = HTMLExporter(extra_loaders=[dl], template_file="footer")
    ---> 17 (body, resources) = exportHTML.from_notebook_node(jake_notebook)
         18 for l in body.split("\n")[-4:]:
         19     print(l)

    NameError: name 'jake_notebook' is not defined

## Real World Uses

@jakevdp uses Pelican and Jupyter Notebook to blog. Pelican will use nbconvert programmatically to generate blog post. Have a look a Pythonic Preambulations for Jake’s blog post.

@damianavila wrote the Nikola Plugin to write blog post as Notebooks and is developing a js-extension to publish notebooks via one click from the web app.