A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: export notebooks as PDFs via CLI (#7997)
Péter Gyarmati50428cf57f11
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 072d21135e..94434a3795 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -12,6 +12,7 @@ from marimo._cli.parse_args import parse_argsfrom marimo._cli.print import echo, greenfrom marimo._cli.utils import prompt_to_overwritefrom marimo._dependencies.dependencies import DependencyManager+from marimo._dependencies.errors import ManyModulesNotFoundErrorfrom marimo._server.api.utils import parse_titlefrom marimo._server.export import (ExportResult,@@ -21,6 +22,7 @@ from marimo._server.export import (export_as_wasm,run_app_then_export_as_html,run_app_then_export_as_ipynb,+ run_app_then_export_as_pdf,)from marimo._server.export.exporter import Exporterfrom marimo._server.utils import asyncio_run@@ -69,7 +71,7 @@ def watch_and_export(if output:output_path = Path(output)- if not force:+ if not force and not watch:if not prompt_to_overwrite(output_path):return@@ -106,6 +108,92 @@ def watch_and_export(asyncio_run(start())+def watch_and_export_bytes(+ marimo_path: MarimoPath,+ output: Path,+ watch: bool,+ export_callback: Callable[[MarimoPath], tuple[bytes | None, bool]],+ force: bool,+) -> None:+ if watch and not output:+ raise click.UsageError(+ "Cannot use --watch without providing "+ + "an output file with --output."+ )++ output_path = Path(output)+ if not force and not watch:+ if not prompt_to_overwrite(output_path):+ return++ def write_data(data: bytes) -> None:+ maybe_make_dirs(output_path)+ output_path.write_bytes(data)++ # No watch, just run once+ if not watch:+ pdf_bytes, did_error = export_callback(marimo_path)+ if pdf_bytes is None:+ raise click.ClickException("Failed to export PDF.")+ write_data(pdf_bytes)+ if did_error:+ raise click.ClickException(+ "Export was successful, but some cells failed to execute."+ )+ return++ # Watch mode: do an initial export before waiting for changes+ pdf_bytes, did_error = export_callback(marimo_path)+ if pdf_bytes is None:+ raise click.ClickException("Failed to export PDF.")+ write_data(pdf_bytes)+ if did_error:+ echo(+ "Warning: Export was successful, but some cells failed to execute.",+ err=True,+ )++ async def on_file_changed(file_path: Path) -> None:+ echo(+ f"File {str(file_path)} changed. Re-exporting to {green(str(output_path))}"+ )+ try:+ # `export_callback` may call `asyncio_run()` internally. This callback+ # runs inside the file watcher's event loop, so we must execute the+ # export in a separate thread to avoid `asyncio.run()` nesting.+ pdf_bytes, did_error = await asyncio.to_thread(+ export_callback, MarimoPath(file_path)+ )+ except Exception as e:+ echo(f"Error: {e}", err=True)+ return++ if pdf_bytes is None:+ echo("Error: Failed to export PDF.", err=True)+ return++ write_data(pdf_bytes)+ if did_error:+ echo(+ "Warning: Export was successful, but some cells failed to execute.",+ err=True,+ )++ async def start() -> None:+ # Watch the file for changes+ watcher = FileWatcher.create(marimo_path.path, on_file_changed)+ echo(f"Watching {green(marimo_path.relative_name)} for changes...")+ watcher.start()+ try:+ # Run forever+ while True: # noqa: ASYNC110+ await asyncio.sleep(1)+ except KeyboardInterrupt:+ watcher.stop()++ asyncio_run(start())++@click.command(help="""Run a notebook and export it as an HTML file.@@ -478,6 +566,155 @@ def ipynb()+ help="""Export a marimo notebook as a PDF file.++Example:++ marimo export pdf notebook.py -o notebook.pdf++Optionally pass CLI args to the notebook:++ marimo export pdf notebook.py -o notebook.pdf -- -arg1 foo -arg2 bar++Requires nbformat and nbconvert to be installed.+"""+)+ "--include-outputs/--no-include-outputs",+ default=True,+ show_default=True,+ type=bool,+ help="Run the notebook and include outputs in the exported PDF file.",+)+ "--webpdf/--no-webpdf",+ default=False,+ show_default=True,+ type=bool,+ help=(+ "Use nbconvert's WebPDF exporter (Chromium). If disabled, marimo will "+ "try standard PDF export (pandoc + TeX) first and fall back to WebPDF."+ ),+)+ "--watch/--no-watch",+ default=False,+ show_default=True,+ type=bool,+ help=_watch_message,+)+ "-o",+ "--output",+ type=click.Path(path_type=Path),+ required=True,+ help="Output PDF file to save to.",+)+ "--sandbox/--no-sandbox",+ is_flag=True,+ default=None,+ show_default=False,+ type=bool,+ help=_sandbox_message,+)+ "-f",+ "--force",+ is_flag=True,+ default=False,+ help="Force overwrite of the output file if it already exists.",+)+ "name",+ required=True,+ type=click.Path(exists=True, file_okay=True, dir_okay=False),+)[email protected]("args", nargs=-1, type=click.UNPROCESSED)+def pdf(+ name: str,+ output: Path,+ watch: bool,+ include_outputs: bool,+ webpdf: bool,+ sandbox: Optional[bool],+ force: bool,+ args: tuple[str],+) -> None:+ """Run a notebook and export it as a PDF file."""+ import sys++ if include_outputs:+ # Set default, if not provided+ if sandbox is None:+ from marimo._cli.sandbox import maybe_prompt_run_in_sandbox++ sandbox = maybe_prompt_run_in_sandbox(name)++ if sandbox:+ from marimo._cli.sandbox import run_in_sandbox++ export_deps = ["nbformat"]+ # Adding webpdf extras to sandbox even if `webpdf` is False, since standard PDF export may fall back to it.+ export_deps.append("nbconvert[webpdf]")+ run_in_sandbox(+ sys.argv[1:],+ name=name,+ additional_deps=export_deps,+ )+ return++ try:+ DependencyManager.require_many(+ "for PDF export",+ DependencyManager.nbformat,+ DependencyManager.nbconvert,+ )+ except ManyModulesNotFoundError as e:+ from marimo._cli.print import bold++ pkgs = " ".join(e.package_names)+ raise click.ClickException(+ f"{e}\n\n"+ f" {green('Tip:')} Install with:\n\n"+ f" pip install {pkgs}\n\n"+ f" or rerun with {bold(f'marimo export pdf {name} --output {output} --sandbox')} (requires uv)"+ ) from None++ cli_args = parse_args(args) if include_outputs else {}++ def export_callback(+ file_path: MarimoPath,+ ) -> tuple[bytes | None, bool]:+ try:+ return asyncio_run(+ run_app_then_export_as_pdf(+ file_path,+ include_outputs=include_outputs,+ webpdf=webpdf,+ cli_args=cli_args,+ argv=list(args) if include_outputs else None,+ )+ )+ except ModuleNotFoundError as e:+ if getattr(e, "name", None) == "playwright":+ raise click.ClickException(+ "Playwright is required for WebPDF export.\n\n"+ f" {green('Tip:')} Install webpdf dependencies with:\n\n"+ " pip install 'nbconvert[webpdf]'\n\n"+ " and install Chromium with:\n\n"+ " python -m playwright install chromium"+ ) from None+ raise+ except Exception as e:+ raise click.ClickException(f"Failed to export PDF: {e}") from None++ return watch_and_export_bytes(+ MarimoPath(name), output, watch, export_callback, force+ )++@click.command(help="""Export a notebook as a WASM-powered standalone HTML file.@@ -634,4 +871,5 @@ export.add_command(html)export.add_command(script)export.add_command(md)export.add_command(ipynb)+export.add_command(pdf)export.add_command(html_wasm)diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex cb89c0a7b3..04066b95df 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -190,6 +190,41 @@ async def run_app_then_export_as_ipynb()+async def run_app_then_export_as_pdf(+ filepath: MarimoPath,+ *,+ include_outputs: bool,+ webpdf: bool,+ cli_args: SerializedCLIArgs,+ argv: list[str] | None,+) -> tuple[bytes | None, bool]:+ file_router = AppFileRouter.from_filename(filepath)+ file_key = file_router.get_unique_file_key()+ assert file_key is not None+ file_manager = file_router.get_file_manager(file_key)++ session_view: SessionView | None = None+ did_error = False++ if include_outputs:+ with patch_html_for_non_interactive_output():+ # Using quiet=True to suppress runtime stdout/stderr since outputs+ # are captured in the session_view and will be included in the PDF+ (session_view, did_error) = await run_app_until_completion(+ file_manager,+ cli_args,+ argv,+ quiet=True,+ )++ pdf_data = Exporter().export_as_pdf(+ app=file_manager.app,+ session_view=session_view,+ webpdf=webpdf,+ )+ return pdf_data, did_error++async def run_app_then_export_as_html(path: MarimoPath,include_code: bool,diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 4ce8228651..3dd32f2622 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -307,13 +307,17 @@ class Exporter:return html, download_filenamedef export_as_pdf(- self, *, app: InternalApp, session_view: SessionView, webpdf: bool+ self,+ *,+ app: InternalApp,+ session_view: SessionView | None,+ webpdf: bool,) -> bytes | None:"""Export notebook as a PDF.Args:app: The app to export- session_view: The session view to export+ session_view: The session view to export. If None, outputs are not included.webpdf: If False, tries standard PDF export (pandoc + TeX) first,falling back to webpdf if deps are not installed. If True, uses webpdfdirectly.diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 889cd31f48..4f88adfc9d 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -842,3 +842,21 @@ class TestExportIpynb:def test_cli_export_html_sandbox_no_prompt(temp_marimo_file: str) -> None:p = _run_export("html", temp_marimo_file, "--no-sandbox")_assert_success(p)+++class TestExportPDF:+ @pytest.mark.skipif(+ DependencyManager.nbformat.has() and DependencyManager.nbconvert.has(),+ reason="This test expects PDF export deps to be missing.",+ )+ def test_export_pdf_missing_dependencies(+ self, temp_marimo_file: str+ ) -> None:+ output_file = temp_marimo_file.replace(".py", ".pdf")+ p = _run_export(+ "pdf", temp_marimo_file, "--output", output_file, "--no-sandbox"+ )+ _assert_failure(p)+ stderr = p.stderr.decode()+ assert "nbconvert" in stderr+ assert "pip install" in stderr