Jupyter nbconvert

7.17.0 · active · verified Sat Mar 28

nbconvert is a powerful tool in the Jupyter ecosystem that converts Jupyter Notebook files (.ipynb) into various other static formats like HTML, LaTeX, PDF, Markdown, reStructuredText, and executable scripts. It is actively maintained and currently supports Python 3.9-3.12. The library sees regular updates, often with several minor releases within major versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically load, optionally execute, and then convert a Jupyter notebook to HTML using nbconvert's Python API. It creates a dummy notebook for a runnable example.

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.exporters import HTMLExporter
import os

# Create a dummy notebook file for demonstration
notebook_content = {
    "cells": [
        {"cell_type": "code", "source": "a = 1\nb = 2\nprint(a + b)", "metadata": {}} 
    ],
    "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.0"}},
    "nbformat": 4,
    "nbformat_minor": 5
}

notebook_filename = "my_notebook.ipynb"
with open(notebook_filename, 'w', encoding='utf-8') as f:
    nbformat.write(nbformat.from_dict(notebook_content), f)

# 1. Load the notebook
with open(notebook_filename, 'r', encoding='utf-8') as f:
    nb = nbformat.read(f, as_version=4)

# 2. (Optional) Execute the notebook
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
tried_nb, _ = ep.preprocess(nb, {'metadata': {'path': '.'}})

# 3. Convert to HTML
html_exporter = HTMLExporter()
body, resources = html_exporter.from_notebook_node(tried_nb)

# 4. Save the converted file
output_filename = "my_notebook.html"
with open(output_filename, 'w', encoding='utf-8') as f:
    f.write(body)

print(f"Notebook '{notebook_filename}' executed and converted to '{output_filename}'")

# Clean up the dummy notebook file
os.remove(notebook_filename)
if os.path.exists('my_notebook.nbconvert.ipynb'): # Preprocessor might save an executed version
    os.remove('my_notebook.nbconvert.ipynb')

view raw JSON →