nbconvert tutorial: Convert ipynb to HTML, PDF, and Python scripts
nbconvert tutorial: Convert ipynb to HTML, PDF, and Python scripts
Jupyter notebooks are fantastic for exploratory work, but eventually you need to share results or reuse your code outside the
interactive environment. nbconvert ships with Jupyter and turns notebooks into polished deliverables that you can send to
stakeholders, publish to the web, or check into source control. This comprehensive guide covers all major export formats with
practical examples for common use cases.
Prerequisites
- A working Python 3.8+ environment with Jupyter Notebook or JupyterLab installed.
- The notebook you want to convert (
analysis.ipynbin the examples below). - For PDF export, LaTeX must be available on your system (MiKTeX, TeX Live, or MacTeX).
Verify that nbconvert is available:
jupyter nbconvert --versionIf the command fails, install it with:
python -m pip install notebook nbconvertAvailable conversion formats
nbconvert supports multiple output formats optimized for different use cases:
| Format | Use case | Command |
|---|---|---|
| HTML | Web sharing, documentation sites | --to html |
| Print-ready reports, formal documents | --to pdf | |
| Python | Source control, module imports, batch scripts | --to python |
| Markdown | Documentation, blog posts, GitHub READMEs | --to markdown |
| LaTeX | Academic papers, custom PDF styling | --to latex |
| Slides (Reveal.js) | Presentations, conference talks | --to slides |
| reStructuredText | Sphinx documentation | --to rst |
| Asciidoc | Technical documentation | --to asciidoc |
| Script | Executable code only (no comments) | --to script |
| Notebook | Clean/execute notebooks | --to notebook |
Let’s explore each format with practical examples.
Export to HTML
Use cases: Sharing analysis with stakeholders, documentation sites, email reports, web dashboards
HTML is the most versatile format for sharing notebook results. It preserves formatting, renders plots, and doesn’t require recipients to have Python installed.
Basic HTML export
jupyter nbconvert analysis.ipynb --to htmlThis creates analysis.html with all cells, outputs, and embedded images.
HTML with custom styling
# Modern JupyterLab look
jupyter nbconvert analysis.ipynb --to html --template lab
# Classic Jupyter Notebook style
jupyter nbconvert analysis.ipynb --to html --template classic
# Custom output name
jupyter nbconvert analysis.ipynb --to html --output report.htmlSelf-contained HTML for email
Create a single HTML file with all images embedded (no external dependencies):
jupyter nbconvert analysis.ipynb --to html --embed-images --output standalone-report.htmlThis is perfect for emailing reports to clients who need to view results offline.
Hide code cells for stakeholders
When sharing with non-technical audiences, hide the code and show only results:
jupyter nbconvert analysis.ipynb --to html --no-inputExecute before converting
If your notebook has stale outputs, run all cells before exporting:
jupyter nbconvert analysis.ipynb --to html --executeBatch convert all notebooks
Convert an entire directory of notebooks to HTML:
jupyter nbconvert notebooks/*.ipynb --to html --output-dir build/htmlAutomate HTML exports
Integrate with CI/CD or task runners. For example, in package.json:
{
"scripts": {
"export:html": "jupyter nbconvert notebooks/*.ipynb --to html --execute --output-dir docs/reports"
}
}Run with npm run export:html to regenerate reports automatically.
Export to PDF
Use cases: Formal reports, print documentation, client deliverables, academic submissions
PDF exports create professional, print-ready documents with consistent formatting across all platforms.
Basic PDF export (LaTeX method)
jupyter nbconvert analysis.ipynb --to pdfRequirements: This method requires a LaTeX distribution (TeX Live, MiKTeX, or MacTeX). If you see xelatex not found, install LaTeX first.
PDF without LaTeX (WebPDF method)
Use Chromium headless rendering to avoid LaTeX dependencies:
# Install pyppeteer first
python -m pip install nbconvert[webpdf]
# Convert using WebPDF
jupyter nbconvert analysis.ipynb --to webpdfWebPDF respects modern CSS styling and works on systems without LaTeX.
Hide code for executive reports
Create stakeholder-friendly PDFs showing only outputs:
# Using LaTeX method
jupyter nbconvert analysis.ipynb --to pdf --no-input
# Using WebPDF method
jupyter nbconvert analysis.ipynb --to webpdf --no-inputExecute and export to PDF
Run all cells, then create a PDF in one command:
jupyter nbconvert analysis.ipynb --to pdf --executeHide specific cells with tags
Tag cells in Jupyter (View > Cell Toolbar > Tags), then exclude them:
# Hide cells tagged with "hide-input"
jupyter nbconvert analysis.ipynb --to pdf \
--TagRemovePreprocessor.remove_input_tags='["hide-input"]'
# Hide cells tagged with "skip"
jupyter nbconvert analysis.ipynb --to pdf \
--TagRemovePreprocessor.remove_cell_tags='["skip"]'Custom branding and templates
Create templates/company.tpl for custom headers, logos, or footers:
((*- extends 'article.tplx' -*))
((* block header *))
\usepackage{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[R]{\includegraphics[width=2cm]{logo.png}}
\fancyfoot[C]{Confidential - Company Name}
((* endblock header *))Then convert with your template:
jupyter nbconvert analysis.ipynb --to pdf --template templates/company.tplExport to Python script
Use cases: Version control, module imports, CI/CD pipelines, refactoring into packages
Python exports convert notebooks into executable .py files, making them easier to version control, test, and import as modules.
Basic Python export
jupyter nbconvert analysis.ipynb --to pythonCreates analysis.py with markdown cells preserved as comments.
Clean Python (code only)
Remove all markdown comments for production code:
jupyter nbconvert analysis.ipynb --to scriptThe script format exports only code cells without any markdown commentary.
Batch convert notebooks to Python
Convert entire project directories for version control:
# Convert all notebooks in a directory
jupyter nbconvert notebooks/*.ipynb --to python --output-dir src/
# Convert and execute to verify they run
jupyter nbconvert notebooks/*.ipynb --to python --execute --output-dir src/Use in version control workflows
Add a pre-commit hook to automatically sync .ipynb and .py files:
# .git/hooks/pre-commit
#!/bin/bash
jupyter nbconvert --to python notebooks/*.ipynb --output-dir src/notebooks/
git add src/notebooks/*.pyThis keeps Python versions up-to-date for easier code review.
Import notebook code as a module
After converting to Python, import functions from your notebook:
# analysis.py was generated from analysis.ipynb
from src.analysis import process_data, create_visualization
# Use notebook functions in production code
df = process_data('new_data.csv')
create_visualization(df)Execute notebooks as scripts
Convert and run immediately:
# Convert to Python and execute
jupyter nbconvert analysis.ipynb --to python --execute --stdout
# Or run the generated Python file
jupyter nbconvert analysis.ipynb --to python && python analysis.pyExport to Markdown
Use cases: GitHub/GitLab documentation, blog posts, static site generators, wiki pages
Markdown exports are perfect for documentation, READMEs, and publishing to platforms that support Markdown.
Basic Markdown export
jupyter nbconvert analysis.ipynb --to markdownCreates analysis.md with code blocks, outputs, and images extracted to a separate folder.
Embed images inline
Keep images embedded as base64 for single-file portability:
jupyter nbconvert analysis.ipynb --to markdown --NbConvertApp.use_output_suffix=FalseUse with static site generators
Convert notebooks for Jekyll, Hugo, or MkDocs:
# For Jekyll blog posts
jupyter nbconvert analysis.ipynb --to markdown --output-dir _posts/
# For Hugo content
jupyter nbconvert analysis.ipynb --to markdown --output-dir content/posts/
# For MkDocs
jupyter nbconvert analysis.ipynb --to markdown --output-dir docs/Extract images to custom folder
jupyter nbconvert analysis.ipynb --to markdown --output analysis.md \
--NbConvertApp.output_files_dir=images/analysisThis creates analysis.md with images stored in images/analysis/.
Export to Reveal.js slides
Use cases: Conference presentations, teaching materials, interactive talks
Create beautiful HTML presentations with slide transitions and speaker notes.
Basic slides export
jupyter nbconvert presentation.ipynb --to slidesOpens in browser with Reveal.js presentation framework.
Serve slides locally
Create and serve the presentation:
jupyter nbconvert presentation.ipynb --to slides --post serveThis automatically opens your browser to view the slideshow.
Control slide structure
In Jupyter, use View > Cell Toolbar > Slideshow to mark cells as:
- Slide - New slide
- Sub-Slide - Vertical slide below current
- Fragment - Appears on click within current slide
- Skip - Hidden from presentation
- Notes - Speaker notes (press ‘s’ during presentation)
Custom slide theme
jupyter nbconvert presentation.ipynb --to slides \
--SlidesExporter.reveal_theme=serifAvailable themes: black, white, league, beige, sky, night, serif, simple, solarized
Export slides with transitions
jupyter nbconvert presentation.ipynb --to slides \
--SlidesExporter.reveal_transition=zoom \
--SlidesExporter.reveal_scroll=trueExport to LaTeX
Use cases: Academic papers, journal submissions, custom PDF layouts
LaTeX export gives you full control over document styling for academic publishing.
Basic LaTeX export
jupyter nbconvert paper.ipynb --to latexCreates paper.tex that you can compile with pdflatex or customize further.
Export with different document classes
# Article format
jupyter nbconvert paper.ipynb --to latex --template article
# Report format with chapters
jupyter nbconvert paper.ipynb --to latex --template reportCompile LaTeX to PDF
# Convert to LaTeX
jupyter nbconvert paper.ipynb --to latex
# Compile with pdflatex
pdflatex paper.texOr combine both steps:
jupyter nbconvert paper.ipynb --to pdfExport to reStructuredText
Use cases: Sphinx documentation, Python package docs, ReadTheDocs
RST format integrates perfectly with Sphinx documentation systems.
Basic RST export
jupyter nbconvert tutorial.ipynb --to rstUse in Sphinx documentation
# Convert notebook to RST
jupyter nbconvert tutorial.ipynb --to rst --output-dir docs/source/
# Build Sphinx docs
cd docs
make htmlAdd to your index.rst:
.. toctree::
:maxdepth: 2
tutorialClean or execute notebooks
Use cases: Clear outputs for version control, run all cells before sharing
The notebook-to-notebook conversion is useful for cleaning or executing notebooks.
Clear all outputs
Remove execution results before committing to git:
jupyter nbconvert analysis.ipynb --to notebook --ClearOutputPreprocessor.enabled=True --output analysis.ipynbOr use the shorthand:
jupyter nbconvert --clear-output --inplace analysis.ipynbExecute and save results
Run all cells and save the notebook with fresh outputs:
jupyter nbconvert analysis.ipynb --to notebook --execute --output analysis.ipynbExecute with timeout
Prevent hanging on long-running cells:
jupyter nbconvert analysis.ipynb --to notebook --execute --ExecutePreprocessor.timeout=300 --output analysis.ipynbThis stops execution after 300 seconds per cell.
Advanced techniques
Convert multiple formats at once
# Generate HTML, PDF, and Python in one command
jupyter nbconvert report.ipynb --to html --to pdf --to pythonUse configuration files
Create jupyter_nbconvert_config.py for project-wide settings:
c = get_config()
# Always execute before converting
c.NbConvertApp.execute = True
# Remove input cells by default
c.TemplateExporter.exclude_input = True
# Custom output directory
c.NbConvertApp.output_base = 'converted/'Run with:
jupyter nbconvert analysis.ipynb --to html --config jupyter_nbconvert_config.pyExtract images and outputs
Extract all images from notebooks:
jupyter nbconvert notebook.ipynb --to markdownImages are saved in notebook_files/ directory.
Programmatic conversion
Use nbconvert in Python scripts:
import nbformat
from nbconvert import HTMLExporter
# Load notebook
with open('analysis.ipynb') as f:
nb = nbformat.read(f, as_version=4)
# Convert to HTML
html_exporter = HTMLExporter()
html_exporter.exclude_input = True
body, resources = html_exporter.from_notebook_node(nb)
# Save to file
with open('report.html', 'w') as f:
f.write(body)Troubleshooting common issues
LaTeX/PDF errors
Error: xelatex not found or pdflatex: command not found
Solution: Install a LaTeX distribution:
- macOS:
brew install --cask mactex-no-gui - Ubuntu/Debian:
sudo apt-get install texlive-xetex texlive-fonts-recommended - Windows: Download and install MiKTeX from miktex.org
Alternative: Use WebPDF instead (--to webpdf)
Missing packages or templates
Error: TemplateNotFound: lab.tpl
Solution: Update nbconvert and notebook:
python -m pip install --upgrade nbconvert notebookExecution timeout
Error: Timeout waiting for execute reply
Solution: Increase timeout or skip execution:
# Increase timeout to 10 minutes
jupyter nbconvert notebook.ipynb --to html --execute --ExecutePreprocessor.timeout=600
# Skip problematic cells by tagging them 'skip' in Jupyter
jupyter nbconvert notebook.ipynb --to html --execute --TagRemovePreprocessor.remove_cell_tags='["skip"]'Images not displaying
Problem: External images don’t show in HTML/PDF exports
Solution: Use --embed-images flag or store images in the same directory:
jupyter nbconvert notebook.ipynb --to html --embed-imagesInteractive widgets not working
Problem: IPywidgets appear as empty boxes in HTML
Solution: Use the --no-input flag to hide widget code, or embed widget state:
jupyter nbconvert notebook.ipynb --to html --template labFor interactive widgets, consider using Voilà or JupyterBook instead.
Memory errors on large notebooks
Problem: Conversion fails on notebooks with large outputs
Solution: Clear outputs first, then re-execute selectively:
# Clear all outputs
jupyter nbconvert --clear-output --inplace notebook.ipynb
# Execute only specific cells manually, then convert
jupyter nbconvert notebook.ipynb --to htmlAutomated exports
Set up scheduled exports with cron (Linux/macOS):
# crontab -e
# Run daily at 2 AM
0 2 * * * cd /path/to/project && jupyter nbconvert notebooks/*.ipynb --to html --execute --output-dir reports/Or use GitHub Actions:
name: Export Notebooks
on:
push:
paths:
- 'notebooks/**'
jobs:
convert:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- run: pip install jupyter nbconvert
- run: jupyter nbconvert notebooks/*.ipynb --to html --output-dir docs/
- uses: actions/upload-artifact@v3
with:
name: converted-notebooks
path: docs/Quick reference
| Task | Command |
|---|---|
| HTML report | jupyter nbconvert notebook.ipynb --to html |
| PDF (no code) | jupyter nbconvert notebook.ipynb --to pdf --no-input |
| Python script | jupyter nbconvert notebook.ipynb --to python |
| Markdown for docs | jupyter nbconvert notebook.ipynb --to markdown |
| Presentation slides | jupyter nbconvert notebook.ipynb --to slides --post serve |
| Execute before export | jupyter nbconvert notebook.ipynb --to html --execute |
| Clear outputs | jupyter nbconvert --clear-output --inplace notebook.ipynb |
| Batch convert | jupyter nbconvert notebooks/*.ipynb --to html --output-dir build/ |
| Multiple formats | jupyter nbconvert notebook.ipynb --to html --to pdf --to python |
Summary
With nbconvert, you can transform Jupyter notebooks into professional deliverables for any audience. Whether you’re creating executive reports with hidden code, publishing documentation to ReadTheDocs, generating slide presentations, or integrating notebooks into CI/CD pipelines, nbconvert provides the flexibility you need. Start with the basic commands above, then explore templates, configuration files, and programmatic conversion as your workflow demands more customization.