### Manual Release Environment Setup Source: https://github.com/jupyter/nbconvert/blob/main/RELEASE.md Prepares the local development environment for a manual release by installing necessary tools and cleaning the repository state. This ensures a clean build environment by removing untracked files and updating the local branch. ```bash pip install pipx git pull origin $(git branch --show-current) git clean -dffx ``` -------------------------------- ### Setup and Run Pre-commit Hooks Source: https://github.com/jupyter/nbconvert/blob/main/CONTRIBUTING.md Installs and configures pre-commit hooks for automatic code formatting and style checks. Includes manual invocation and fixing of committed files. ```bash pip install pre-commit pre-commit install ``` ```bash pre-commit run ``` ```bash pre-commit run --all-files ``` ```bash pre-commit run --hook-stage manual ``` -------------------------------- ### Serve nbconvert Documentation Locally Source: https://github.com/jupyter/nbconvert/blob/main/docs/README.md Starts a local Python HTTP server to display the nbconvert documentation. Navigate to http://localhost:8000 in your browser after running this command. ```python python -m http.server 8000 ``` -------------------------------- ### Build and Upload Distribution Packages Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/development_release.rst Installs the build tool, creates source and wheel distributions, and uploads them to PyPI using twine. This ensures the package is ready for distribution. ```bash pip install build python -m build . twine upload dist/* ``` -------------------------------- ### Install Pandoc Source: https://github.com/jupyter/nbconvert/blob/main/README.md Instructions for installing the pandoc utility, which is a dependency for nbconvert, on Debian/Ubuntu-based systems and macOS. ```bash sudo apt-get install pandoc ``` ```bash brew install pandoc ``` -------------------------------- ### Install nbconvert for Development Source: https://github.com/jupyter/nbconvert/blob/main/README.md Steps to clone the nbconvert repository and install it in editable mode for development purposes. This allows for direct modifications and testing. ```bash git clone https://github.com/jupyter/nbconvert.git cd nbconvert pip install -e . ``` -------------------------------- ### Configure Execution Timeout via CLI Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/execute_api.rst Demonstrates how to pass configuration options (traitlets) to the ExecutePreprocessor via the command line. This example sets a custom timeout for cell execution. ```bash jupyter nbconvert --ExecutePreprocessor.timeout=600 --to notebook --execute mynotebook.ipynb ``` -------------------------------- ### Install nbconvert Dependencies Source: https://github.com/jupyter/nbconvert/blob/main/CONTRIBUTING.md Installs nbconvert with all dependencies for testing and features, or specifically for testing. ```bash pip install -e '.[all]' ``` ```bash pip install -e '.[test]' ``` ```bash pip install -e '.[docs]' ``` -------------------------------- ### Create a Custom Preprocessor Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/nbconvert_library.ipynb Shows how to subclass nbconvert.preprocessors.Preprocessor to implement custom logic. This example creates a preprocessor that filters notebook cells based on start and end indices. ```python 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""" 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 ``` -------------------------------- ### Build nbconvert Documentation Locally (Windows) Source: https://github.com/jupyter/nbconvert/blob/main/docs/README.md Steps to build the nbconvert documentation locally on Windows. This involves setting up a conda environment, installing the package with development dependencies, and using make.bat to build the HTML documentation. ```bash cd docs conda env create -f environment.yml source activate nbconvert_docs pip install -e '..[docs]' make.bat html ``` -------------------------------- ### Extract Binary Outputs with ExtractOutputPreprocessor Source: https://context7.com/jupyter/nbconvert/llms.txt This example demonstrates using the ExtractOutputPreprocessor with HTMLExporter to extract binary outputs like images from a notebook. The extracted outputs are saved as separate files, and the notebook content is updated to reference these files. It also shows how to display an extracted image. ```python import nbformat from nbconvert import HTMLExporter from traitlets.config import Config # Read notebook with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) # Enable figure extraction c = Config() c.HTMLExporter.preprocessors = ["nbconvert.preprocessors.ExtractOutputPreprocessor"] html_exporter = HTMLExporter(config=c) (body, resources) = html_exporter.from_notebook_node(notebook) # resources["outputs"] contains extracted figures for filename, data in resources.get("outputs", {}).items(): print(f"Extracted: {filename} ({len(data)} bytes)") with open(filename, "wb") as f: f.write(data) # Display an extracted image from IPython.display import Image Image(data=resources["outputs"]["output_3_0.png"], format="png") ``` -------------------------------- ### Build nbconvert Documentation Locally (Linux/macOS) Source: https://github.com/jupyter/nbconvert/blob/main/docs/README.md Steps to build the nbconvert documentation locally on Linux or macOS. This involves setting up a conda environment, installing the package with development dependencies, and using make to build the HTML documentation. ```bash cd docs conda env create -f environment.yml source activate nbconvert_docs pip install -e '..[docs]' make html ``` -------------------------------- ### Create Nested VBox and HBox Layouts Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create complex layouts using nested VBox and HBox widgets. This example arranges two VBoxes horizontally within an HBox. ```python import ipywidgets as widgets items = [widgets.Label(str(i)) for i in range(4)] left_box = widgets.VBox([items[0], items[1]]) right_box = widgets.VBox([items[2], items[3]]) widgets.HBox([left_box, right_box]) ``` -------------------------------- ### Create and Display an Output Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Introduces the Output widget, which captures and displays standard output, standard error, and rich output generated by IPython. Refer to the official documentation for detailed examples. ```python import ipywidgets as widgets # Example usage (actual output capture not shown in snippet) widgets.Output() ``` -------------------------------- ### Customizing HTML Theme Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Shows how to apply custom themes to the HTML output generated by nbconvert's 'lab' template. This involves installing a theme package and specifying it with the --theme option. ```bash # Install a theme (example: jupyterlab-miami-nights) pip install jupyterlab-miami-nights # Use the installed theme jupyter nbconvert --to html --theme jupyterlab_miami_nights notebook.ipynb ``` -------------------------------- ### Define template configuration in conf.json Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/customizing.rst Example of a conf.json file used to define base template inheritance, supported mimetypes, and enabled preprocessors for an nbconvert template. ```json { "base_template": "lab", "mimetypes": { "text/html": true }, "preprocessors": { "100-pygments": { "type": "nbconvert.preprocessors.CSSHTMLHeaderPreprocessor", "enabled": true }, "500-reveal": { "type": "nbconvert.exporters.slides._RevealMetadataPreprocessor", "enabled": true } } } ``` -------------------------------- ### Convert Notebook to reveal.js Slides with Local reveal.js Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Converts a Jupyter notebook to reveal.js slides, specifying a local copy of reveal.js using the `--reveal-prefix` flag. This enables features that depend on a local reveal.js installation, such as speaker notes. ```shell jupyter nbconvert your_talk.ipynb --to slides --reveal-prefix reveal.js ``` -------------------------------- ### Create Custom Templates for nbconvert Output Source: https://context7.com/jupyter/nbconvert/llms.txt This example demonstrates how to create custom Jinja2 templates to control the output formatting of nbconvert. It shows how to extend built-in templates, override specific blocks like the header and footer, and use a `DictLoader` to load the custom template string. The custom template is then applied during the export process. ```python import nbformat from nbconvert import HTMLExporter from jinja2 import DictLoader # Read notebook with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) # Define custom template extending lab template custom_template = """ {%- extends 'lab/index.html.j2' -%} {% block header %}

My Custom Header

Generated from Jupyter Notebook

{{ super() }} {% endblock header %} {% block footer %} {% endblock footer %} """ # Create template loader template_loader = DictLoader({"custom_template": custom_template}) # Use custom template html_exporter = HTMLExporter( extra_loaders=[template_loader], template_file="custom_template" ) (body, resources) = html_exporter.from_notebook_node(notebook) with open("custom_output.html", "w", encoding="utf-8") as f: f.write(body) ``` -------------------------------- ### WebPDF Export Process Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Command to generate a PDF by first converting the notebook to HTML, then rendering the HTML using a headless browser (Chromium via Playwright), and finally exporting to PDF. Requires 'nbconvert[webpdf]' installation. ```bash jupyter nbconvert --to webpdf notebook.ipynb ``` -------------------------------- ### Implement Custom Preprocessors for nbconvert Source: https://context7.com/jupyter/nbconvert/llms.txt This section details how to create custom preprocessors for nbconvert by subclassing the `Preprocessor` class. Two examples are provided: `CellSelectorPreprocessor` to select a range of cells and `MetadataInjectorPreprocessor` to add custom metadata to cells. These custom preprocessors can then be integrated into the nbconvert configuration. ```python import nbformat from nbconvert.preprocessors import Preprocessor from nbconvert import HTMLExporter from traitlets import Integer, Unicode from traitlets.config import Config class CellSelectorPreprocessor(Preprocessor): """Select a range of cells from the notebook.""" start = Integer(0, help="First cell index to include").tag(config=True) end = Integer(-1, help="Last cell index to include (-1 for end)").tag(config=True) def preprocess(self, nb, resources): self.log.info(f"Selecting cells from {self.start} to {self.end}") if self.end == -1: nb.cells = nb.cells[self.start:] else: nb.cells = nb.cells[self.start:self.end] return nb, resources class MetadataInjectorPreprocessor(Preprocessor): """Inject custom metadata into all cells.""" author = Unicode("", help="Author name to inject").tag(config=True) def preprocess_cell(self, cell, resources, index): if self.author: cell.metadata["author"] = self.author cell.metadata["cell_index"] = index return cell, resources # Use custom preprocessor c = Config() c.CellSelectorPreprocessor.start = 2 c.CellSelectorPreprocessor.end = 10 c.HTMLExporter.preprocessors = [CellSelectorPreprocessor] with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) html_exporter = HTMLExporter(config=c) (body, resources) = html_exporter.from_notebook_node(notebook) ``` -------------------------------- ### Universal Notebook Export with export() Function Source: https://context7.com/jupyter/nbconvert/llms.txt Illustrates the versatile `export()` function in nbconvert for converting notebooks to various formats using different exporters. It shows how to list available exporters, get specific exporter classes, and perform exports from notebook objects, filenames, or file streams. ```python import nbformat from nbconvert.exporters import export, get_exporter, get_export_names from nbconvert import HTMLExporter, MarkdownExporter print(get_export_names()) HTMLExporterClass = get_exporter("html") exporter = HTMLExporterClass() with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) (output, resources) = export(HTMLExporter, notebook) html_exporter = HTMLExporter(template_name="classic") (output, resources) = export(html_exporter, notebook) (output, resources) = export(MarkdownExporter, "mynotebook.ipynb") with open("mynotebook.ipynb", "r", encoding="utf-8") as f: (output, resources) = export(HTMLExporter, f) ``` -------------------------------- ### Configure Notebook Conversion via File Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Demonstrates how to specify a list of notebooks to convert using a Python configuration file. This approach is helpful for managing complex conversion tasks or when dealing with many notebooks. ```python c = get_config() c.NbConvertApp.notebooks = ["notebook1.ipynb", "notebook2.ipynb"] ``` -------------------------------- ### Configure and Use Custom Exporter Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/nbconvert_library.ipynb Demonstrates how to instantiate a configuration object to register a custom preprocessor and apply it to an RSTExporter. ```python c = Config() c.PelicanSubCell.start = 4 c.PelicanSubCell.end = 6 c.RSTExporter.preprocessors = [PelicanSubCell] pelican = RSTExporter(config=c) print(pelican.from_notebook_node(jake_notebook)[0]) ``` -------------------------------- ### Convert Multiple Notebooks Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Shows how to convert multiple notebooks at once using wildcard patterns or by listing them individually on the command line. This streamlines batch conversion processes. ```bash jupyter nbconvert notebook*.ipynb ``` ```bash jupyter nbconvert notebook1.ipynb notebook2.ipynb ``` -------------------------------- ### Run nbconvert Tests Source: https://github.com/jupyter/nbconvert/blob/main/README.md Command to install nbconvert with testing dependencies and run the test suite using pytest. This is useful for verifying installations and development changes. ```bash pip install nbconvert[test] py.test --pyargs nbconvert ``` -------------------------------- ### Create and Display an HTML Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create an HTML widget to render basic HTML content. It includes parameters for value, placeholder, and description. ```python import ipywidgets as widgets widgets.HTML( value="Hello World", placeholder="Some HTML", description="Some HTML", ) ``` -------------------------------- ### Create and Display an Image Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Demonstrates how to display an image using the Image widget. It requires reading image data from a file in binary mode and specifying the image format, width, and height. ```python import ipywidgets as widgets file = open("testimage.png", "rb") image = file.read() widgets.Image( value=image, format="png", width=300, height=400, ) ``` -------------------------------- ### Python ipywidgets: Toggle Button Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Provides an example of the ToggleButton widget, which functions as a clickable button that maintains a boolean state (pressed or not pressed). It supports tooltips and styling. ```python import ipywidgets as widgets widgets.ToggleButton( value=False, description="Click me", disabled=False, button_style="", # 'success', 'info', 'warning', 'danger' or '' tooltip="Description", icon="check", ) ``` -------------------------------- ### Create and Display a Button Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create a Button widget with customizable properties like description, tooltip, and icon. It also highlights available button styles. ```python import ipywidgets as widgets widgets.Button( description="Click me", disabled=False, button_style="", # 'success', 'info', 'warning', 'danger' or '' tooltip="Click me", icon="check", ) ``` -------------------------------- ### Create and Display a Label Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Demonstrates how to create a Label widget to display text, often used alongside other controls for custom descriptions. It shows integration within an HBox. ```python import ipywidgets as widgets widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()]) ``` -------------------------------- ### Create an Integer Slider Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Unexecuted_widget.ipynb This snippet initializes an IntSlider widget with custom range, step, and display settings. It requires the ipywidgets library to be installed and active in the Jupyter environment. ```python import ipywidgets as widgets widgets.IntSlider( value=7, min=0, max=10, step=1, description="Test:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) ``` -------------------------------- ### Python ipywidgets: Integer Range Slider Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Provides an example of an IntRangeSlider, allowing users to select a range of integer values. It's configured with minimum, maximum, and step values. ```python import ipywidgets as widgets widgets.IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description="Test:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) ``` -------------------------------- ### Command Line Conversions with nbconvert Source: https://context7.com/jupyter/nbconvert/llms.txt Demonstrates various command-line operations for converting Jupyter Notebooks to different formats using nbconvert. Includes options for execution, input/output control, and template usage. ```bash jupyter nbconvert --to html mynotebook.ipynb ``` ```bash jupyter nbconvert --to pdf mynotebook.ipynb ``` ```bash jupyter nbconvert --to webpdf mynotebook.ipynb --allow-chromium-download ``` ```bash jupyter nbconvert --to markdown mynotebook.ipynb ``` ```bash jupyter nbconvert --to slides presentation.ipynb ``` ```bash jupyter nbconvert --to html --execute mynotebook.ipynb ``` ```bash jupyter nbconvert --to html --no-input mynotebook.ipynb ``` ```bash jupyter nbconvert --to html --no-prompt mynotebook.ipynb ``` ```bash jupyter nbconvert --clear-output --inplace mynotebook.ipynb ``` ```bash jupyter nbconvert --to latex mynotebook.ipynb ``` ```bash jupyter nbconvert --to script mynotebook.ipynb ``` ```bash jupyter nbconvert --to rst mynotebook.ipynb ``` ```bash jupyter nbconvert --to asciidoc mynotebook.ipynb ``` ```bash jupyter nbconvert --to html --output-dir ./output mynotebook.ipynb ``` ```bash jupyter nbconvert --to html --template classic mynotebook.ipynb ``` ```bash cat mynotebook.ipynb | jupyter nbconvert --to html --stdin --stdout > output.html ``` -------------------------------- ### Python API: PDFExporter Usage Source: https://context7.com/jupyter/nbconvert/llms.txt Demonstrates how to use the PDFExporter class in Python to convert Jupyter Notebooks to PDF format. This method relies on LaTeX compilation and requires xelatex to be installed. ```python import nbformat from nbconvert import PDFExporter with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) pdf_exporter = PDFExporter() try: (pdf_data, resources) = pdf_exporter.from_notebook_node(notebook) with open("output.pdf", "wb") as f: f.write(pdf_data) except OSError as e: print(f"LaTeX not found: {e}") ``` -------------------------------- ### Command Line Interface Source: https://context7.com/jupyter/nbconvert/llms.txt The primary CLI tool for converting notebooks. Use the --to flag to specify output format and various other flags for customization. ```APIDOC ## CLI Usage ### Description Convert Jupyter notebooks using the command line interface. ### Method N/A (CLI) ### Parameters - **--to** (string) - Required - The output format (html, pdf, markdown, script, etc.) - **--execute** (flag) - Optional - Run the notebook before conversion. - **--output-dir** (string) - Optional - Specify the directory for output files. - **--template** (string) - Optional - Use a custom template for conversion. ### Request Example `jupyter nbconvert --to html mynotebook.ipynb --execute` ``` -------------------------------- ### Jinja Template Block for stdout Output Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/architecture.rst An example of a Jinja template block used in nbconvert HTML exports. It demonstrates how to wrap stdout text in a div and apply the 'ansi2html' filter to process the output. ```html {% block stream_stdout -%}
{{- output.text | ansi2html -}}
{%- endblock stream_stdout %} ``` -------------------------------- ### Configure a FileUpload Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Demonstrates the configuration of a FileUpload widget, which allows users to upload files. Key parameters include accepted file types and whether multiple files are allowed. ```python import ipywidgets as widgets widgets.FileUpload( accept="", # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False, # True to accept multiple files upload else False ) ``` -------------------------------- ### Initialize Custom Package Directory Structure Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/external_exporters.rst Creates the necessary directory and file structure for a new nbconvert exporter package using bash commands. ```bash mkdir -p mypackage/mypackage/templates touch mypackage/LICENSE.md touch mypackage/setup.py touch mypackage/mypackage/__init__.py touch mypackage/mypackage/templates/test_template.tpl ``` -------------------------------- ### HTML Export with Templates and Options Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Demonstrates various ways to export a notebook to HTML using nbconvert, including different templates ('lab', 'classic', 'basic') and options like embedding images. ```bash # Default 'lab' template jupyter nbconvert --to html notebook.ipynb # 'classic' template jupyter nbconvert --to html --template classic notebook.ipynb # 'basic' template jupyter nbconvert --to html --template basic notebook.ipynb # Embed images as base64 URLs jupyter nbconvert --to html --embed-images notebook.ipynb ``` -------------------------------- ### Create and Display a ColorPicker Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Illustrates the creation of a ColorPicker widget for selecting colors. It allows setting an initial value, description, and concise mode. ```python import ipywidgets as widgets widgets.ColorPicker(concise=False, description="Pick a color", value="blue", disabled=False) ``` -------------------------------- ### Execute Configuration File for Conversion Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Applies the configuration specified in a Python file (e.g., mycfg.py) to perform notebook conversions. This allows for advanced customization of the nbconvert process. ```bash jupyter nbconvert --config mycfg.py ``` -------------------------------- ### Compare Notebook Exporter Outputs Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/nbconvert_library.ipynb Demonstrates how to compare the resource outputs of a standard HTMLExporter versus a customized one. It highlights the addition of an 'outputs' field when custom preprocessors are applied. ```python (_, 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())) ``` -------------------------------- ### Customize Markdown Output with Jinja2 Template Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/customizing.rst This example shows how to override Jinja2 blocks in a custom nbconvert template to modify the rendering of markdown output. It specifically wraps traceback lines, streams, and text data in fenced code blocks with the 'output' tag. ```jinja {% extends 'markdown/index.md.j2' %} {%- block traceback_line -%} ```output {{ line.rstrip() | strip_ansi }} ``` {%- endblock traceback_line -%} {%- block stream -%} ```output {{ output.text.rstrip() }} ``` {%- endblock stream -%} {%- block data_text scoped -%} ```output {{ output.data['text/plain'].rstrip() }} ``` {%- endblock data_text -%} ``` -------------------------------- ### Execute Notebook and Allow Errors Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Demonstrates how to execute a notebook during conversion and continue even if errors occur. The output from exceptions will be included in the cell output when --allow-errors is used with --execute. ```bash jupyter nbconvert --execute --allow-errors mynotebook.ipynb ``` -------------------------------- ### List Available Pygments Styles (CLI) Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/highlighting.rst Command-line utility to list all available Pygments styles on the system. This helps in choosing a style for nbconvert. ```bash pygmentize -L styles ``` -------------------------------- ### Select nbconvert template via CLI Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/customizing.rst Demonstrates how to use the --template option with the nbconvert command line interface to specify a custom template for export. ```bash jupyter nbconvert --to html --template reveal ``` -------------------------------- ### Serve reveal.js Slides with Local HTTPS Server Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Converts a Jupyter notebook to reveal.js slides and serves them using a local HTTPS server via the `--post serve` flag. This is necessary for features like timers to function correctly, in addition to having a local reveal.js copy. ```shell jupyter nbconvert your_talk.ipynb --to slides --reveal-prefix reveal.js --post serve ``` -------------------------------- ### Initialize NumPy and Matplotlib Environment Source: https://github.com/jupyter/nbconvert/blob/main/tests/exporters/files/notebook2.ipynb Imports the necessary libraries and sets up the inline plotting backend for Jupyter notebooks. ```python %pylab inline import numpy as np ``` -------------------------------- ### Write Notebook Output to Disk with FilesWriter Source: https://context7.com/jupyter/nbconvert/llms.txt Demonstrates how to use the FilesWriter to save the main notebook output and extracted resources (like images) to the file system. It shows configuration for different output directories and exporters (HTML, RST). ```python import nbformat from nbconvert import HTMLExporter, RSTExporter from nbconvert.writers import FilesWriter from traitlets.config import Config # Read notebook with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) # Export with extracted figures c = Config() c.HTMLExporter.preprocessors = ["nbconvert.preprocessors.ExtractOutputPreprocessor"] html_exporter = HTMLExporter(config=c) (body, resources) = html_exporter.from_notebook_node(notebook) # Configure writer writer = FilesWriter() writer.build_directory = "./output" # Write main file and all resources notebook_name = "mynotebook" output_path = writer.write(body, resources, notebook_name=notebook_name) print(f"Written to: {output_path}") # RST export with figures rst_exporter = RSTExporter() (body, resources) = rst_exporter.from_notebook_node(notebook) writer = FilesWriter(build_directory="./rst_output") writer.write(body, resources, notebook_name="mynotebook") # Creates: ./rst_output/mynotebook.rst and ./rst_output/output_*.png ``` -------------------------------- ### Initialize SymPy and Define Symbols Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/notebook1.ipynb Imports necessary SymPy functions and initializes pretty printing. Defines symbolic variables x, y, and z for use in expressions. ```python from sympy import * from sympy import init_printing init_printing() ``` ```python x, y, z = symbols("x y z") ``` -------------------------------- ### Create and Display a Controller Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create a Controller widget, enabling the use of a game controller as an input device within the Jupyter environment. The index parameter specifies the controller. ```python import ipywidgets as widgets widgets.Controller( index=0, ) ``` -------------------------------- ### Convert Notebook to RST Format Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/nbconvert_library.ipynb Demonstrates converting a notebook node to RST format using an rst_exporter. It highlights how binary resources are separated from the text body. ```python (body, resources) = rst_exporter.from_notebook_node(jake_notebook) print(body[:970] + "...") ``` -------------------------------- ### Registering Custom Exporters in setup.py Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/external_exporters.rst Demonstrates how to register custom exporter classes within a Python package's setup.py file using the 'nbconvert.exporters' entry point. This allows users to invoke custom exporters by name via the command line. ```python setup( # ... entry_points={ "nbconvert.exporters": [ "simple = mymodule:SimpleExporter", "detail = mymodule:DetailExporter", ], } ) ``` -------------------------------- ### Execute Notebook Cells with ExecutePreprocessor Source: https://context7.com/jupyter/nbconvert/llms.txt Shows how to use the `ExecutePreprocessor` to run all code cells within a notebook and capture their outputs. This is useful for generating reports with up-to-date results. It covers execution with default and specific kernels, setting timeouts, and enabling error tolerance. ```python import nbformat from nbconvert.preprocessors import ExecutePreprocessor from nbconvert import HTMLExporter from traitlets.config import Config with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) ep = ExecutePreprocessor(timeout=600) ep.preprocess(notebook, {"metadata": {"path": "./"}}) with open("executed_notebook.ipynb", "w", encoding="utf-8") as f: nbformat.write(notebook, f) c = Config() c.ExecutePreprocessor.enabled = True c.ExecutePreprocessor.timeout = 600 c.ExecutePreprocessor.allow_errors = True html_exporter = HTMLExporter(config=c) (body, resources) = html_exporter.from_notebook_node(notebook) ``` ```python from traitlets.config import Config from nbconvert import HTMLExporter c = Config() c.ExecutePreprocessor.enabled = True c.ExecutePreprocessor.kernel_name = "python3" html_exporter = HTMLExporter(config=c) ``` -------------------------------- ### Create and Configure a Tab Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create a Tab widget, which displays child widgets in separate tabs. Tab titles are set similarly to the Accordion widget. ```python import ipywidgets as widgets tab_contents = ["P0", "P1", "P2", "P3", "P4"] children = [widgets.Text(description=name) for name in tab_contents] tab = widgets.Tab() tab.children = children for i in range(len(children)): tab.set_title(i, str(i)) tab ``` -------------------------------- ### Create and Display an HBox Layout Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Illustrates the HBox widget for arranging child widgets horizontally. It takes a list of widgets and lays them out in a row. ```python import ipywidgets as widgets items = [widgets.Label(str(i)) for i in range(4)] widgets.HBox(items) ``` -------------------------------- ### Build Release Artifacts Source: https://github.com/jupyter/nbconvert/blob/main/RELEASE.md Cleans the distribution directory and builds the project artifacts. This step prepares the package for distribution by generating the necessary files in the dist folder. ```bash rm -rf dist pipx run build . ``` -------------------------------- ### Preview All Pygments Styles with Python Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/highlighting.rst Python script to iterate through all available Pygments styles, highlight a sample Python code snippet using each style, and print the result. This allows for visual comparison of different highlighting themes. ```python from pygments.styles import get_all_styles from pygments.formatters import Terminal256Formatter from pygments.lexers import PythonLexer from pygments import highlight code = """ import os def function(test=1): if test in [3,4]: print(test) """ for style in get_all_styles(): highlighted_code = highlight(code, PythonLexer(), Terminal256Formatter(style=style)) print(f"{style}:\n{highlighted_code}") ``` -------------------------------- ### Create and Display a DatePicker Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Shows how to create a DatePicker widget for selecting dates. Note that its compatibility may vary across browsers, with potential issues in Safari. ```python import ipywidgets as widgets widgets.DatePicker(description="Pick a Date", disabled=False) ``` -------------------------------- ### Create and Configure an Accordion Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Demonstrates the Accordion widget, which displays multiple widgets, each in its own collapsible pane. Titles for each pane can be set using `set_title`. ```python import ipywidgets as widgets accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()]) accordion.set_title(0, "Slider") accordion.set_title(1, "Text") accordion ``` -------------------------------- ### Create and Display an HTMLMath Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Illustrates the creation of an HTMLMath widget for rendering mathematical expressions using LaTeX, combined with HTML. It supports inline and display math. ```python import ipywidgets as widgets widgets.HTMLMath( value=r"Some math and HTML: \(x^2\) and $$\frac{x+1}{x-1}$$", placeholder="Some HTML", description="Some HTML", ) ``` -------------------------------- ### Inspect Jupyter paths Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/customizing.rst Command to list all configured Jupyter directories, including search paths for templates and configuration files. ```bash jupyter --paths ``` -------------------------------- ### In-Place Notebook Conversion Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Converts a notebook and overwrites the original file. Use this command with caution as it will replace the input notebook with the converted version. ```bash jupyter nbconvert --to notebook mynb --output mynb ``` -------------------------------- ### Convert Notebook to Standard Output Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Converts a notebook to markdown format and sends the output directly to standard output instead of creating a file. This is useful for piping the output to other commands or for quick previews. ```bash jupyter nbconvert --to markdown notebook.ipynb --stdout ``` -------------------------------- ### Enabling HTML Output (nbconvert 5.x behavior) Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst To replicate the default HTML output behavior of nbconvert versions prior to 6.0, explicitly use the --to=html argument. ```bash jupyter nbconvert --to=html notebook.ipynb ``` -------------------------------- ### Create and Display a Box Layout Widget Source: https://github.com/jupyter/nbconvert/blob/main/tests/files/Widget_List.ipynb Demonstrates the Box widget, a container for arranging other widgets. It takes a list of widgets as its `children` property and arranges them by default. ```python import ipywidgets as widgets items = [widgets.Label(str(i)) for i in range(4)] widgets.Box(items) ``` -------------------------------- ### Manual Versioning and Tagging Source: https://github.com/jupyter/nbconvert/blob/main/RELEASE.md Updates the project version using hatch and creates a signed git tag for the release. It requires user input for the version number and applies the tag to the current commit. ```bash echo "Enter new version" read new_version pipx run hatch version ${new_version} git tag -a ${new_version} -m "Release ${new_version}" ``` -------------------------------- ### Create Reveal.js Slideshows Source: https://context7.com/jupyter/nbconvert/llms.txt Converts notebooks into interactive HTML slideshows using Reveal.js, respecting cell metadata for slide structure. ```python from nbconvert import SlidesExporter slides_exporter = SlidesExporter() (body, resources) = slides_exporter.from_notebook_node(notebook) with open("presentation.slides.html", "w", encoding="utf-8") as f: f.write(body) ``` -------------------------------- ### Access and Display Extracted Notebook Resources Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/nbconvert_library.ipynb Shows how to inspect the resources dictionary to identify extracted binary figures and display them using IPython's Image object without disk I/O. ```python sorted(resources["outputs"].keys()) from IPython.display import Image Image(data=resources["outputs"]["output_3_0.png"], format="png") ``` -------------------------------- ### Export Notebooks using WebPDFExporter Source: https://context7.com/jupyter/nbconvert/llms.txt Converts notebooks to PDF using a headless Chromium browser via Playwright. Includes configurations for automatic browser downloads, pagination, and sandbox settings. ```python import nbformat from nbconvert import WebPDFExporter from traitlets.config import Config with open("mynotebook.ipynb", "r", encoding="utf-8") as f: notebook = nbformat.read(f, as_version=4) webpdf_exporter = WebPDFExporter() (pdf_data, resources) = webpdf_exporter.from_notebook_node(notebook) # Configuration for containerized environments c = Config() c.WebPDFExporter.disable_sandbox = True c.WebPDFExporter.allow_chromium_download = True webpdf_exporter = WebPDFExporter(config=c) (pdf_data, resources) = webpdf_exporter.from_notebook_node(notebook) ``` -------------------------------- ### Run Dejavu Command Line Tool Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/dejavu.rst Demonstrates how to run the Dejavu tool from the command line to convert a Jupyter notebook to static output. It mirrors nbconvert functionality and accepts similar command-line options. ```bash jupyter dejavu notebook.ipynb ``` ```bash jupyter dejavu --show-input notebook.ipynb ``` -------------------------------- ### Clone reveal.js for Local Slideshows Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst This command sequence clones the reveal.js repository and checks out a specific version (3.5.0) to be used locally with nbconvert. This is a prerequisite for enabling features like speaker notes that require a local copy of reveal.js. ```shell git clone https://github.com/hakimel/reveal.js.git cd reveal.js git checkout 3.5.0 cd .. ``` -------------------------------- ### LaTeX Export with Metadata Source: https://github.com/jupyter/nbconvert/blob/main/docs/source/usage.rst Illustrates exporting a notebook to LaTeX format. It also shows how to include metadata like authors, title, and date within the notebook's JSON configuration for the LaTeX header. ```json { "authors": [ { "name": "Jane Doe" }, { "name": "John Doe" } ], "date": "January 2023", "title": "Annual Data Report 2022", "kernelspec": { }, "language_info": { } } ```