AboutBlogMediaTags

nbconvert tutorial: Convert ipynb to HTML, PDF, and Python scripts

Runcell Team,

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

Verify that nbconvert is available:

jupyter nbconvert --version

If the command fails, install it with:

python -m pip install notebook nbconvert

Available conversion formats

nbconvert supports multiple output formats optimized for different use cases:

FormatUse caseCommand
HTMLWeb sharing, documentation sites--to html
PDFPrint-ready reports, formal documents--to pdf
PythonSource control, module imports, batch scripts--to python
MarkdownDocumentation, blog posts, GitHub READMEs--to markdown
LaTeXAcademic papers, custom PDF styling--to latex
Slides (Reveal.js)Presentations, conference talks--to slides
reStructuredTextSphinx documentation--to rst
AsciidocTechnical documentation--to asciidoc
ScriptExecutable code only (no comments)--to script
NotebookClean/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 html

This 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.html

Self-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.html

This 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-input

Execute before converting

If your notebook has stale outputs, run all cells before exporting:

jupyter nbconvert analysis.ipynb --to html --execute

Batch convert all notebooks

Convert an entire directory of notebooks to HTML:

jupyter nbconvert notebooks/*.ipynb --to html --output-dir build/html

Automate 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 pdf

Requirements: 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 webpdf

WebPDF 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-input

Execute and export to PDF

Run all cells, then create a PDF in one command:

jupyter nbconvert analysis.ipynb --to pdf --execute

Hide 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.tpl

Export 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 python

Creates analysis.py with markdown cells preserved as comments.

Clean Python (code only)

Remove all markdown comments for production code:

jupyter nbconvert analysis.ipynb --to script

The 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/*.py

This 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.py

Export 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 markdown

Creates 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=False

Use 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/analysis

This 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 slides

Opens in browser with Reveal.js presentation framework.

Serve slides locally

Create and serve the presentation:

jupyter nbconvert presentation.ipynb --to slides --post serve

This automatically opens your browser to view the slideshow.

Control slide structure

In Jupyter, use View > Cell Toolbar > Slideshow to mark cells as:

Custom slide theme

jupyter nbconvert presentation.ipynb --to slides \ --SlidesExporter.reveal_theme=serif

Available 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=true

Export 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 latex

Creates 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 report

Compile LaTeX to PDF

# Convert to LaTeX jupyter nbconvert paper.ipynb --to latex # Compile with pdflatex pdflatex paper.tex

Or combine both steps:

jupyter nbconvert paper.ipynb --to pdf

Export 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 rst

Use in Sphinx documentation

# Convert notebook to RST jupyter nbconvert tutorial.ipynb --to rst --output-dir docs/source/ # Build Sphinx docs cd docs make html

Add to your index.rst:

.. toctree:: :maxdepth: 2 tutorial

Clean 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.ipynb

Or use the shorthand:

jupyter nbconvert --clear-output --inplace analysis.ipynb

Execute and save results

Run all cells and save the notebook with fresh outputs:

jupyter nbconvert analysis.ipynb --to notebook --execute --output analysis.ipynb

Execute with timeout

Prevent hanging on long-running cells:

jupyter nbconvert analysis.ipynb --to notebook --execute --ExecutePreprocessor.timeout=300 --output analysis.ipynb

This 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 python

Use 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.py

Extract images and outputs

Extract all images from notebooks:

jupyter nbconvert notebook.ipynb --to markdown

Images 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:

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 notebook

Execution 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-images

Interactive 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 lab

For 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 html

Automated 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

TaskCommand
HTML reportjupyter nbconvert notebook.ipynb --to html
PDF (no code)jupyter nbconvert notebook.ipynb --to pdf --no-input
Python scriptjupyter nbconvert notebook.ipynb --to python
Markdown for docsjupyter nbconvert notebook.ipynb --to markdown
Presentation slidesjupyter nbconvert notebook.ipynb --to slides --post serve
Execute before exportjupyter nbconvert notebook.ipynb --to html --execute
Clear outputsjupyter nbconvert --clear-output --inplace notebook.ipynb
Batch convertjupyter nbconvert notebooks/*.ipynb --to html --output-dir build/
Multiple formatsjupyter 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.

© Runcell.RSS